【发布时间】:2020-06-03 12:27:02
【问题描述】:
我有多对多的关系。我有三张桌子:
posts
posts_tag
tags
表“帖子”具有标准字段。
“posts_tag”表的结构:
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->bigInteger('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
});
表“标签”的结构:
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
关系在模型中定义:
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
}
}
我调用方法$tag->posts:
public function getPostsByTag($id)
{
$tag = Tag::find($id);
dd($tag->posts);
}
我只得到一个数组:
Illuminate\Database\Eloquent\Collection {#571 ▼
#items: array:1 [▶]
}
我会感谢任何帮助的朋友!如果你对我的英语感到抱歉,我正在学习中!
【问题讨论】:
-
我很抱歉没有这样写,所以你写的那样,所以有!
-
$id的值是多少?并且数据透视表是posts_tag或post_tag? -
这将是我过滤的ID!数据透视表是“posts_tag”!
-
您将哪个
$id发送给getPostsByTag?我的意思是价值。 -
我有路线:
Route::get('/tag/{id?}', 'PostController@getPostsByTag')->name('blog.getPostsByTag');
标签: laravel relationship laravel-6