Laravel 6.9 belongsToMany 关系 return 一个集合
Laravel 6.9 belongsToMany Relationships return one collection
我有多对多关系。我有三个 tables:
posts
posts_tag
tags
Table "posts" 有标准字段。
结构table "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');
});
结构table "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 [▶]
}
screenshot database
朋友们的帮助我将不胜感激!如果你对我的英语感到抱歉,我正在学习中!
在你的标签模式中
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
}
}
在你的Post模态
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);
}
我有多对多关系。我有三个 tables:
posts
posts_tag
tags
Table "posts" 有标准字段。
结构table "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');
});
结构table "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 [▶]
}
screenshot database
朋友们的帮助我将不胜感激!如果你对我的英语感到抱歉,我正在学习中!
在你的标签模式中
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
}
}
在你的Post模态
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);
}