Laravel雄辩的关系没有访问第二个表

问题描述 投票:0回答:1

我有2张桌子:

电子邮件:email_id,姓名

email_templates:template_id,template_mid,template_lang,template_subject,template_mail

Template_mid是外键并与emails.id相关联

我的模特:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Email extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Indicates primary key column.
     *
     * @var bool
     */
    protected $primaryKey = "email_id";

    public function template()
    {
        return $this->hasOne('App\Email_template', 'template_mid', 'email_id');
    }
}

Email_template

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Email_template extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * Indicates primary key column.
     *
     * @var bool
     */
    protected $primaryKey = "template_id";
}

当我在我的控制器中运行它时:

public function index()
    {

        $emails = Email::all();
        dd($emails);
    }

我无法访问模板方法,我只有id,在转储结果中的主题。我怎样才能解决这个问题?

php laravel
1个回答
2
投票

相关模型不会自动加载。您可以使用with()加载它们,也可以单独加载:

Email::with('template')->get();

要么

foreach($emails as $email) 
{ 
      dd($email->template); 
}
© www.soinside.com 2019 - 2024. All rights reserved.