[英]Laravel relationships empty, wrong defined?
稍作休息后,我想繼續我自己的項目。 但是,我現在坐在這里已經兩個小時了,不知道我做錯了什么或者我的錯誤在哪里。
所以,我有可以創建產品、評論和喜歡評論的用戶。 但是,當我想檢索用戶發布的所有產品或評論或用戶喜歡的所有評論時,我總是得到沒有內容的 hasMany 關系(我在儀表板刀片中調用了$user->products()
,由UserController
):
Illuminate\Database\Eloquent\Relations\HasMany {#662 ▼
#foreignKey: "products.user_id"
#localKey: "id"
#query: Illuminate\Database\Eloquent\Builder {#656 ▶}
#parent: App\User {#654 ▶}
#related: App\Product {#663 ▼
#with: array:1 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
}
誰能告訴我哪里出錯了?
用戶 model:
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
use HasSettingsField;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the products record associated with the user.
*/
public function products()
{
return $this->hasMany('App\Product');
}
/**
* Get the comments record associated with the user.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
/**
* Get the comment likes record associated with the user.
*/
public function commentlikes()
{
return $this->hasMany('App\CommentLike');
}
}
產品 model:
class Product extends Model
{
/**
* The relationships that should always be loaded.
*
* @var array
*/
protected $with = ['comments'];
/**
* Get the user that owns the product.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
評論 model:
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
return view('pages.userDashboard')->with([
'user' => $user
]);
}
我認為像財產一樣訪問它就可以了。 不要像方法一樣調用它,如果你這樣做,它將調用方法。
$user->products;
$user->comments;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.