我有一个Posts
表,其中包含可以为1或0的列anonym
。我使用Eloquent选择帖子,并像这样加入用户:
$posts = Post::with(
array('user'=>function($query){
$query->select('id','username');
}))
->with('category')
->withCount('likes')
->orderBy('id', 'DESC')
->paginate(25);
回报看起来像这样:
"data": [
{
"id": 116,
"user_id": 3,
...
"anonym": 1,
"likes_count": 0,
"user": {
"id": 3,
"username": "Max"
},
"category": null,
},
现在,当posts表中
anonym
的值是1
时,我希望用户名不要是“最大”但“匿名”。我尝试使用原始查询,但无法正常工作。雄辩有可能吗?
编辑:
我按照建议尝试了以下方法:
array('user'=>function($query){
$query->select(DB::raw("IF(`posts`.`anonym` = 0, `users`.`username`, 'Anonym') as username"));
}))
但我收到错误,找不到posts.anonym:
找不到列:1054'字段列表'中的未知列'posts.anonym'(SQL:选择IF(
posts
。anonym
= 0,users
。username
,'Anonym'))作为来自其中(1)中的users
。users
) 最佳答案
您可以尝试这样的事情:
$posts = Post::join('users', 'users.id', '=', 'posts.user_id')
->select(
'posts.*',
DB::raw('IF(`posts`.`anonym`, `users`.`username`, "Anonym") as username')
)
->with('category')
->withCount('likes')
->orderBy('id', 'DESC')
->paginate(25);