将所有带有标签的文章加载到一个数组中 Laravel eloquent polymorphic relationship.

问题描述 投票:0回答:1

我需要获取所有存在于我的表中的带有标签的帖子到一个数组中。正如你所看到的,这个查询只获取有标签的帖子,但我需要所有的帖子,即使它们没有任何标签。此外,我还需要有一个 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']
        }


php laravel eloquent polymorphic-associations
1个回答
1
投票
return self::$model::
    with('tags')->
    whereNotNull('title')->
    whereNotNull('content')->
    whereNotNull('author')->
    whereNotNull('category')->
    whereNotNull('img_url')->
    get()->
    toArray();

1
投票

你使用 has 顾名思义,这个方法检查是否有标签关系,用with代替。

public function getItemsWithTags(array $attr)
{
        return self::$model::
        whereNotNull('title')->
        whereNotNull('content')->
        whereNotNull('author')->
        whereNotNull('category')->
        whereNotNull('img_url')->
        with('tags')->
        get()->
        toArray();
}
© www.soinside.com 2019 - 2024. All rights reserved.