laravel关联问题与用户模型

时间:2016-06-22 17:58:29

标签: php laravel-5 laravel-5.2

我有关联广告表,用户如何向用户展示 数据。它显示我试图获取非对象属性的错误 关联。

表:

  1. 广告
  2. 用户(默认Laravel)
  3. 在用户模型中:

        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] => )

1 个答案:

答案 0 :(得分:0)

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

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

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