php - 如何在 laravel mysql 中将单个选择中的选择值分组为数组?
问题描述
我试图从使用 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++;
}
解决方案
你的问题的关键是你认为你正在使用Eloquent,但你不是——你正在使用Query Builder。Eloquent 处理模型之间的关系,因此您无需考虑表格。如果你正在使用,join()
那么你就没有使用 Eloquent。
据我所知,您从 a 开始City
,选择Business
与该城市相关的,然后Post
从? 中随机选择 10 个Business
?事情有点不清楚,因为您似乎使用了非常规的表名和列名,但希望这会让您知道从哪里开始。
第一步是建立关系;除了典型的“ City
has many Business
”和“ Business
has many Post
”之外,您还需要在 and 之间建立直接关系City
,Post
如下所示:
class City extends Model
{
public function posts()
{
return $this->hasManyThrough(Post::class, Business::class);
}
}
一旦建立了这种关系,您应该能够通过以下方式获得所需的内容:
$city = City::find($city_id);
$data = $city
->posts()
->inRandomOrder()
->limit(10)
->with("business:id,name,img_profile,username")
->get();
推荐阅读
- python - sql alchemy在where函数中的多个条件
- android - 如果设备中未安装 Twitter 应用程序,Twitter 登录将不起作用
- r - R中的for循环与if/else
- html - 如何在 HTML 的 div 中显示 XML 代码
- django - auth.views.Loginview 显示“__init__() 有一个意外的关键字参数 'request'”
- redirect - Sitecore - 类似 URL 的 301 重定向
- javascript - 根据 ID 设置元素的数据属性
- java - 我无法在 Spring 的后台运行该方法
- aspnetboilerplate - 使用 abp 的多语句事务中不允许创建数据库语句
- node.js - 来自 url 的参数添加到静态目录路径中