【问题标题】:laravel assocation issue with user modellaravel 与用户模型的关联问题
【发布时间】:2026-02-11 02:05:01
【问题描述】:

我有与用户关联的广告表,我如何向用户展示 数据。它显示我尝试获取非对象的属性时出错 协会。

表格:

  1. 广告
  2. 用户(默认 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


    【解决方案1】:

    要获得您应该使用的所有广告,Ad::all() 而不是 Ad::get()

    更新您的Ad 模型,因为一位用户有一个广告:

    public function ads()
    {
        return $this->hasOne('App\Ad','user_id');
    }
    

    【讨论】:

    • 我在做 Ad::all() 时做到了,它给了我同样的问题。我想打印用户名 echo $ad->user->name;但是这行代码不能正常工作。当我打印数组 $ad->user 时,它会显示数据。但不知道如何提取它。
    • 打印整个数组
    • 请分享数组数据
    • 我在上面与您分享答案。无论如何感谢召唤的帮助
    • 删除答案,而是通过编辑将数组数据发布到您的问题中。