首先我要实现的目标非常简单:我想使用Laravel 5中的关系belongsTo从另一个表中获取值。像这样
<?= $email->contact->first_name; ?>
但这根本不起作用,相反,我得到了这个错误:试图获取非对象的属性。但是,当我执行print_r($ email)时,它向我显示$ email实际上是一个对象......所以我现在真的不明白。
这是我控制器中的(部分):
$emails = Email::where('user_id', '=', Auth::user()->id)->take(6)->orderBy('created_at', 'desc')->get();
这就是我的看法:
foreach($emails as $key => $email) {
echo $email->contact->first_name; ?>
}
这是我的模型电子邮件
public function contact()
{
return $this->belongsTo('App\Contact', 'contact_id');
}
如您所见,我在belongsTo方法中使用了第二个参数,即'contact_id',因为我不想使用'user_id'作为外键。
编辑:
这是我输出的print_r($ email):
App\Email Object ( [connection:protected] => [table:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [id] => 88 [user_id] => 1 [group_id] => 1 [contact_id] => 79 [reminder_id] => 31 [subject] => Test task #3 [view] => 0 [view_hash] => $2y$10$NZ3B.UUqtRRl2opH5UwXOeRNeRROeZGdid6Crs4ShT1VptbZJS.iu [content] => blablabla
编辑2:
这是我输出的print_r($ email-&gt; contact):
App\Contact Object ( [fillable:protected] => Array ( [0] => title [1] => content ) [table:protected] => contacts [connection:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [incrementing] => 1 [timestamps] => 1 [attributes:protected] => Array ( [id] => 86 [user_id] => 1 [group_id] => 1 [first_name] => Matthieu [last_name] => Boistoule [email] => m.boistoule@gmail.com [phone] => [company] => [title] => [website] => [industry] => [address] => [city] => [country] => [province] => [postal_code] => [lead_source] => [notes] => [created_at] => 2015-06-04 12:13:00 [updated_at] => 2015-06-04 12:13:00 ) [original:protected] => Array ( [id] => 86 [user_id] => 1 [group_id] => 1 [first_name] => Matthieu [last_name] => Boistoule [email] => m.boistoule@gmail.com [phone] => [company] => [title] => [website] => [industry] => [address] => [city] => [country] => [province] => [postal_code] => [lead_source] => [notes] => [created_at] => 2015-06-04 12:13:00 [updated_at] => 2015-06-04 12:13:00 ) [relations:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [appends:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [casts:protected] => Array ( ) [touches:protected] => Array ( ) [observables:protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 )