簡體   English   中英

用戶模型的laravel關聯問題

[英]laravel assocation issue with user model

我有與用戶的關聯廣告表,如何顯示用戶數據。 它向我顯示了嘗試獲取非對象關聯屬性的錯誤。

表格:

  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對象([可填充:受保護] =>數組([0] =>名稱[1] =>電話[2] =>電子郵件[3] =>密碼[4] =>角色)[隱藏:受保護] =>數組([0] =>密碼[1] => Remember_token)[連接:受保護] => [表:受保護] => [primaryKey:受保護] => id [每頁:受保護] => 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] =>數組([id] => 1 [name] => irfan [email] => irfan0786@gmail.com [phone] => 43434 [password] => $ 2y $ 10 $ dnUuC9yxQwSHcpWy1oZlpuxaU33eBz1VYCPFQgfJYtncDiroDro >用戶[remember_token] => x3l3x1tkXUB3I7KiRggPRclnCR5JGnDLlzCxZxeAmfpGCYFR0ylSrKNwSSuy [created_at] => 2016-06-12 17:42:36 [updat ed_at] => 2016-06-22 03:26:28)[relations:protected] => Array()[visible:protected] => Array()[appends:protected] => Array()[guarded:protected] =>數組([0] => *)[dates:protected] => Array()[dateFormat:protected] => [casts:protected] => Array()[touches:protected] => Array()[observables :protected] => Array()[with:protected] => Array()[morphClass:protected] => [exists] => 1 [wasRecentlyCreated] =>)

要獲取您應該使用的所有廣告,請Ad::all()而不是Ad::get()

由於一位用戶擁有一個廣告,因此更新您的Ad模型:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM