【问题标题】:How to use "With" in subqueries laravel eloquent with condition?如何在子查询laravel eloquent with condition中使用“With”?
【发布时间】:2018-09-03 11:49:30
【问题描述】:

我正在尝试向我的项目添加新功能,以便能够匿名添加推文,因此我需要检查公共字段是否 = 0,返回没有用户或 null 用户对象的推文!

如何将“with”与 OrWhere 或类似内容一起使用?

我已经通过合并集合来做到这一点,但我需要更有效的查询来做到这一点 当我尝试返回所有集合的用户数据的 OrWhere()->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);           

【问题讨论】:

    标签: php mysql laravel eloquent laravel-5.6


    【解决方案1】:

    我已经通过在模型中添加方法来计算这个解决方案检查这个条件并返回取决于这个条件

        $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;
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 2018-07-11
      相关资源
      最近更新 更多