我有关联广告表,用户如何向用户展示 数据。它显示我试图获取非对象属性的错误 关联。
表:
在用户模型中:
public function ads()
{
return $this->hasMany('App\Ad','user_id');
}
In Ad Model
public function user()
{
return $this->belongsTo('App\User');
}
in Routes
Route::get('/ads',function(){
$ads = Ad::get();
//print_r($ads);
foreach ($ads as $ad) {
echo $ad->user->name;// issue here
}
});
我在print_r($ad->user)
;
App \ User Object([fillable:protected] => Array([0] => name [1] => phone [2] => email [3] => password [4] = >角色)[隐藏:受保护] =>数组([0] =>密码[1] => remember_token)[connection:protected] => [table:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [递增] => 1 [时间戳] => 1 [属性:受保护] =>数组([id] => 1 [名称] =>伊尔凡[电子邮件] => irfan0786@gmail.com [电话] => 43434 [口令] => $ 2Y $ 10 $ dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [作用] =>用户[remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updated_at] => 2016-06-22 03:26:28)[original:protected] =>数组([id] => 1 [name] => irfan [email] => irfan0786@gmail.com [phone] => 43434 [密码] => $ 2y $ 10 $ dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [role] =>用户[remember_token] => x 3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updated_at] => 2016-06-22 03:26:28)[关系:受保护] => Array()[visible:protected] => Array()[appends:protected] => Array()[guarded:protected] =>数组([0] => *)[日期:受保护] => Array()[dateFormat:protected] => [casts:protected] => Array()[touches:protected] => Array()[observables:protected] => Array()[with:protected] => Array()[morphClass:protected] => [exists] => 1 [wasRecentlyCreated] => )
答案 0 :(得分:0)
要获取您应使用的所有广告,Ad::all()
不是Ad::get()
。
更新您的Ad
模型,因为一个用户只有一个广告:
public function ads()
{
return $this->hasOne('App\Ad','user_id');
}