setrelation方法在Laravel中不起作用 [英] setrelation method doesn't work in laravel

查看:85
本文介绍了setrelation方法在Laravel中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户关系是:

    public function country()
    {
        return $this->belongsTo(Country::class);
    }

,查询为:

  $user = User::with('country')->first();

我要检查国家/地区是否为空,用默认数据或其他任何内容替换

I want to check if the country is empty replace that with a default data or anything

所以首先我尝试这样:

if(empty($user->country)){
$user->country = "some default value";
}

并且在搜索后无法正常工作:

and It didn't work after searching I try this :

if(empty($user->country)){
$user->setRelation('country' , 'some default value');
}

再次对我不起作用."setRelation"删除用户对象中的国家/地区密钥

and again it doesn't work for me. the "setRelation" remove the country key in the user's object

推荐答案

如果雄辩的结果 relation 键中收到空/null,则可以设置set defaultOject 如下:

If empty / null received in eloquent result relation key, then set defaultOject can be set as follows:

对于单一关系:

$modelInstance = $modelInstance->setRelation('relationName', $relationModelObject)

对于多重关系:

$modelInstance = $modelInstance->setRelation('relationName', collect([$relationModelObject]))

多个关系示例:

$defaultMedia = new Media;
$defaultMedia->id = 0;
$defaultMedia->file_name = 'defaultImage.jpg';

$result = Post::with('media')->get();

$result->transform(function ($post, $key) use($defaultMedia) {
    if($post->media->count() == 0) {
        $post->setRelation('media', collect([$defaultMedia]));
    }
    return $post;
});

return $result;

现在,在最终 $ result 中,当 relation 返回 null 时,您将获得 $ defaultMedia .

Now, in final $result you shall get $defaultMedia when relation returned null.

这篇关于setrelation方法在Laravel中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆