我有很多对很多关系。我有三个表:
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 [▶]
}
如果有任何帮助的朋友,我将不胜感激!如果您对我的英语感到抱歉,我正在学习中!
在您的代码模式中
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
}
}
在您的发布方式中
class Post extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id');
}
}
在您的控制器中
public function getPostsByTag($id)
{
$tag = Post::with('tags')->find($id);
dd($tag);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句