【发布时间】:2021-05-19 21:27:19
【问题描述】:
我正在尝试使用 eloquent 从查询中获取此信息。
$data = [
"user" => [
"img_profile" => "profileimage",
"username" => "myusername"
],
"description" => "postdescription",
"img" => "postimg"
];
我设法使用以下 php 代码得到了这个,但我想从查询中得到这个,有什么办法吗?
$posts = posts::join('business', 'posts.user_id', '=', 'business.user_id')
->join('cities', 'business.city_id', '=', 'cities.id')
->select(
'posts.description as description',
'posts.img as img',
'business.name as name',
'business.img_profile as img_profile',
'business.username as username'
)
->where('business.city_id', $city)
->inRandomOrder()
->limit('10')
->get();
foreach($posts as $post){
$data[$i] = [
"user" => [
"username" => $post->username,
"img_profile" => $post->img_profile
],
"description" => $post->description,
"img" => $post->img
];
$i++;
}
【问题讨论】:
-
你是怎么得到
$posts的? -
@miken32 $posts = posts::join('business','posts.user_id','=','business.user_id') ->join('cities','business.city_id ','=','cities.id') ->select('posts.description as description','posts.img as img', 'business.name as name','business.img_profile as img_profile','business .username 作为用户名') ->where('business.city_id',$city) ->inRandomOrder() ->limit('10') ->get();
-
嗯,我看到的第一个危险信号是模型之间没有建立关系。您不必手动加入
business表,而不必手动加入Post::with("business", "city")之类的东西。 Eloquent 可以做到这一点,但您无法仅使用查询构建器来做您想做的事情。
标签: php laravel eloquent laravel-query-builder