php - 将所有带有标签的帖子加载到数组中 Laravel 雄辩的多态关系
问题描述
我需要将我的表中存在的所有帖子及其所有标签提取到一个数组中。正如您在下面看到的,此查询仅获取具有标签的帖子,但我需要所有帖子,即使它们没有任何标签。此外,我需要tag:[]
在我的数组中有一个变量,但我不知道如何在一个查询中获取所有带有标签的帖子。
先感谢您。
public function getItemsWithTags(array $attr)
{
return self::$model::
whereNotNull('title')->
whereNotNull('content')->
whereNotNull('author')->
whereNotNull('category')->
whereNotNull('img_url')->
has('tags')->
get()->
toArray();
}
class BaseModel extends Model
{
protected $table;
protected $primaryKey;
use SoftDeletes;
}
class BlogModel extends BaseModel
{
protected $table = 'blog';
protected $primaryKey = 'id';
public function tags()
{
return $this->morphToMany(TagsModel::class,'taggable',null,null,'tag_id');
}
}
class TagsModel extends BaseModel
{
protected $table = 'tags';
protected $primaryKey = 'id';
protected $fillable = ['name'];
public function blog()
{
return $this->morphedByMany(BlogModel::class,"taggable");
}
}
此查询的输出:
{
"id": 28,
"title": "dfg",
"content": "<ul>\n<li>rdgrdgf</li>\n<li>dfg</li>\n<li>dg</li>\n<li>dgf</li>\n<li>dfg</li>\n</ul>",
"author": "gd",
"category": "Design",
"img_url": "uploads/post/Screenshot from 2020-03-27 20-34-42_7dc41dca1ebc4dabcb921fc7f4c4744a.png",
"created_at": "2020-05-03T18:47:38.000000Z",
"updated_at": "2020-05-03T18:47:38.000000Z",
"deleted_at": null,
"user_id": 1,
"category_id": 7
}
我需要的是:
{
"id": 28,
"title": "dfg",
"content": "<ul>\n<li>rdgrdgf</li>\n<li>dfg</li>\n<li>dg</li>\n<li>dgf</li>\n<li>dfg</li>\n</ul>",
"author": "gd",
"category": "Design",
"img_url": "uploads/post/Screenshot from 2020-03-27 20-34-42_7dc41dca1ebc4dabcb921fc7f4c4744a.png",
"created_at": "2020-05-03T18:47:38.000000Z",
"updated_at": "2020-05-03T18:47:38.000000Z",
"deleted_at": null,
"user_id": 1,
"category_id": 7,
"tags":['tag1','tag2']
}
解决方案
return self::$model::
with('tags')->
whereNotNull('title')->
whereNotNull('content')->
whereNotNull('author')->
whereNotNull('category')->
whereNotNull('img_url')->
get()->
toArray();
推荐阅读
- c# - Visual Studio 不支持代码解析或生成,因为它不包含在支持代码的项目中
- javascript - 如何仅使用 Javascript 在 div 中显示整个选择元素
- ios - CoreStore 重新获取谓词 NSFetchRequest 问题
- php - 如何从excel文件中导入数据并识别子类别
- javascript - 使用 javascript 打印页面元素时指定文件名
- angular - CognitoUser:“可观察”类型上不存在属性“属性”
' - angular - 如何避免“意外模块 'HttpClientModule' ...注释”错误?
- c++ - 如何确保目录对象的读取索引在 FATFS 中倒带?
- docker - 子目录中的 Dockerfile 导致构建上下文异常之外的禁止路径
- node.js - 如何在 NestJS 服务中测试猫鼬?