首页 > 解决方案 > 将所有带有标签的帖子加载到数组中 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']
        }


标签: phplaraveleloquentpolymorphic-associations

解决方案


return self::$model::
    with('tags')->
    whereNotNull('title')->
    whereNotNull('content')->
    whereNotNull('author')->
    whereNotNull('category')->
    whereNotNull('img_url')->
    get()->
    toArray();

推荐阅读