如何在子查询中使用“with”laravel elounk with condition?

jm81lzqq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(370)

我正在尝试添加新的功能到我的项目,以便能够添加匿名推文,所以我需要检查如果公共字段=0,返回没有用户或空用户对象的推文!
我怎么能用with,where之类的词呢?
我已经通过合并集合实现了这一点,但是当我尝试使用where()->with()返回所有集合的用户数据时,我需要更高效的查询来实现这一点with()中的数据只附带条件吗?怎么做?谢谢

$tweets = Tweet::where(function ($query) {
                    $query->where('public',1);
                    $query->where('hashtag_id', request('hashtag_id'));
                })->with([
                    'user' => function ($query) {
                        $query->select('id', 'name', 'username', 'photo', 'verified')->withTrashed();
                    },
                    'hashtag' => function ($query) {
                        $query->withTrashed();
                    },
                  ])->  where(function ($query) {
                        $query->whereRaw('DATE_ADD(created_at,INTERVAL expiration_time SECOND) >= "' . Carbon::now()->toDateTimeString() . '" or expiration_time = 0');})
                        ->withCount(['replies'])->orderBy('created_at', 'desc')->get();
$tweets2 = Tweet::where(function ($query) {
                    $query->where('public',0);
                    $query->where('hashtag_id', request('hashtag_id'));
                })->with(['hashtag' => function ($query) {
                        $query->withTrashed();
                    },
                    ])-> where(function ($query) {
                        $query->whereRaw('DATE_ADD(created_at,INTERVAL expiration_time SECOND) >= "' . Carbon::now()->toDateTimeString() . '" or expiration_time = 0');})
                        ->withCount(['replies'])->orderBy('created_at', 'desc')->get();

$tweets = $tweets->merge($tweets2);
zc0qhyus

zc0qhyus1#

我通过在模型中添加方法来计算这个解决方案,检查这个条件并根据这个条件返回

$tweets = Tweet::Where(function ($query) {
        $query->where('hashtag_id', request('hashtag_id'));
    })->with([
        'hashtag' => function ($query) {
            $query->withTrashed();
        },
    ])->where(function ($query) {
        $query->whereRaw('DATE_ADD(created_at,INTERVAL expiration_time SECOND) >= "' . Carbon::now()->toDateTimeString() . '" or expiration_time = 0');})
        ->withCount(['replies'])->orderBy('created_at', 'desc')->get();
    foreach($tweets as $tweet){
        $tweet->user = $tweet->GetPublic();
    }

这就是模型中的方法

public function GetPublic()
    {
        if($this->public == 1)
        {   $user = $this->user;
            return $user;
        }
        else{
            return null;
        }
    }

相关问题