laravel - Laravel 6.9 belongsToMany 关系返回一个集合
问题描述
我有多对多的关系。我有三张桌子:
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);
}
推荐阅读
- reactjs - 如何安装 rn-fetch-blob
- flutter - 在颤动中添加下拉按钮时出错
- python - Python:.strip() 方法未按预期工作
- wdk - 如何在 WDK 中同时处理 winnt.h 和 ntstatus.h?
- docker - Traefik + Consul 不使用 TRAEFIK DEFAULT CERT 在复制模式下生成 SSL 证书
- python - 查找文件中的所有 url
- java - 自动从appium获取设备参数
- python - Flask + Sqlite3 不正确的字符串格式
- javascript - 有没有办法在 React js 中改变渲染内部的状态?
- c# - 为什么重新加载页面时通过 StreamWriter 写入文件的文本不会保存?(Xamarin)