【发布时间】:2020-04-12 19:27:07
【问题描述】:
稍作休息后,我想继续我自己的项目。但是,我现在坐在这里已经两个小时了,不知道我做错了什么或我的错误在哪里。
所以,我有可以创建产品、评论和喜欢 cmets 的用户。
但是,当我想检索用户发布的所有产品或 cmets 或用户喜欢的所有 cmets 时,我总是得到没有内容的 hasMany 关系(我在由UserController 调用的仪表板刀片中调用了$user->products()) :
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 [▶]
}
}
谁能告诉我哪里出错了?
用户模型:
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');
}
}
产品型号:
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');
}
}
评论模型:
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
return view('pages.userDashboard')->with([
'user' => $user
]);
}
【问题讨论】:
标签: php mysql laravel eloquent