Загрузить все сообщения с их тегами в массив Laravel красноречивый полиморф c отношения - PullRequest
0 голосов
/ 06 мая 2020

Мне нужно получить все сообщения, существующие в моей таблице, со всеми их тегами в массив. Как вы видите ниже, этот запрос просто получает сообщения с тегами, но мне нужны все сообщения, даже если у них нет тегов. Кроме того, мне нужно иметь переменную 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']
        }


Ответы [ 2 ]

1 голос
/ 06 мая 2020

Вы используете has, как следует из названия, этот метод проверяет, существует ли связь тегов, используйте вместо этого:

public function getItemsWithTags(array $attr)
{
        return self::$model::
        whereNotNull('title')->
        whereNotNull('content')->
        whereNotNull('author')->
        whereNotNull('category')->
        whereNotNull('img_url')->
        with('tags')->
        get()->
        toArray();
}
1 голос
/ 06 мая 2020
return self::$model::
    with('tags')->
    whereNotNull('title')->
    whereNotNull('content')->
    whereNotNull('author')->
    whereNotNull('category')->
    whereNotNull('img_url')->
    get()->
    toArray();
...