【发布时间】:2026-02-11 02:05:01
【问题描述】:
我有与用户关联的广告表,我如何向用户展示 数据。它显示我尝试获取非对象的属性时出错 协会。
表格:
- 广告
- 用户(默认 Laravel)
在用户模型中:
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] => role ) [hidden :protected] => Array ( [0] => password [1] => remember_token ) [connection:protected] => [table:protected] => [primaryKey:protected] => id [perPage:protected] => 15 [递增] => 1 [时间戳] => 1 [属性:受保护] => 数组 ([id] => 1 [名称] => irfan [电子邮件] => irfan0786@gmail.com [电话] => 43434 [密码] => $ 2Y $ 10 $ dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [作用] =>用户[remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016年6月12日17点42分36秒[的updated_at] => 2016年6月22日3点26: 28 ) [original:protected] => Array ( [id] => 1 [name] => irfan [email] => irfan0786@gmail.com [phone] => 43434 [password] => $2y$10$dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDivmDfqym [角色] => 用户 [remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [上dated_at] => 2016-06-22 03:26:28 ) [relations:protected] => Array () [visible:protected] => Array () [appends:protected] => Array () [guarded:protected] => Array ( [0] => * ) [dates:protected] => Array ( ) [dateFormat:protected] => [casts:protected] => Array ( ) [touches:protected] => Array ( ) [observables :protected] => Array ( ) [with:protected] => Array ( ) [morphClass:protected] => [exists] => 1 [wasRecentlyCreated] => )
【问题讨论】:
标签: php laravel-5 laravel-5.2