我有两张桌子:
电子邮件: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,在转储结果中有主题。我该如何解决这个问题?
答案 0 :(得分:2)
不会自动加载相关模型。您可以使用with()
加载它们,也可以单独加载它们:
Email::with('template')->get();
或
foreach($emails as $email)
{
dd($email->template);
}