我是 Laravel 新手。我正在尝试在两个表之间建立关系。
我的数据库表
评论表
$table->increments('id');
$table->text('comment');
$table->string('shop_name','80');
$table->bigInteger('product_id');
$table->timestamps();
comments_images 表
$table->increments('id');
$table->bigInteger('comment_id');
$table->string('images','255');
$table->string('shop_name','80');
$table->timestamps();
==========================
评论模型
public function images()
{
return $this->hasMany(Comments_images::class,'comment_id');
}
评论图像模型
public function comments()
{
return $this->belongsTo(Comment::class);
}
我尝试像这样返回相关数据
return Comments_images::find(439)->comments()->get();
return Comment::find(880)->images()->get();
return (new Comment())->images()->get();
它们都不起作用!
我应该做什么?
最佳答案
您是否正确使用了命名空间?例如,“App\Comments_images”。此外,模型最好保持单数形式,例如“Comment”或“Comment_Image”。我提出这个问题是因为你不一致,这可能会导致错误。最后一件事是使用类的字符串,而不是返回实际的类。请参阅下面的示例,并注意大写,并且我没有在某些内容上添加“s”。
// in Comment model
public function images()
{
return $this->hasMany('App\Comments_Image','comment_id');
}
// in Comments_Image model
public function comment()
{
return $this->belongsTo('App\Comment', 'id', 'comment_id');
}
编辑:随意使用 Comment::class
而不是字符串 'App\Comment'
- 它解析为相同的内容并且与编辑器导航配合得更好,自动完成和其他有用的东西。
关于php - laravel Eloquent 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187142/