我正在尝试向项目中添加新功能,以便能够匿名添加推文,因此我需要检查public field = 0,返回没有用户或空用户对象的推文!
我如何在OrWhere或类似的东西中使用“ with”?
我已经通过合并集合来做到这一点,但是我需要更高效的查询来做到这一点 当我尝试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);
答案 0 :(得分:0)
我已经通过在模型中添加方法来解决此问题,请检查这种情况并根据这种情况返回
$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;
}
}