首页 > 解决方案 > 如何在 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++;
}

标签: phplaraveleloquentlaravel-query-builder

解决方案


你的问题的关键是你认为你正在使用Eloquent,但你不是——你正在使用Query Builder。Eloquent 处理模型之间的关系,因此您无需考虑表格。如果你正在使用,join()那么你就没有使用 Eloquent。

据我所知,您从 a 开始City,选择Business与该城市相关的,然后Post从? 中随机选择 10 个Business?事情有点不清楚,因为您似乎使用了非常规的表名和列名,但希望这会让您知道从哪里开始。

第一步是建立关系;除了典型的“ Cityhas many Business”和“ Businesshas many Post”之外,您还需要在 and 之间建立直接关系CityPost如下所示:

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();

推荐阅读