如何将 select 值分组为单个 select 作为 laravel mysql 中的数组?

How can I group select values in a single select as array in 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, but you are not – you are using Query Builder。 Eloquent 处理模型之间的关系,因此您永远不必考虑 table。如果您使用 join() 那么您就没有使用 Eloquent.

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

第一步是建立关系;除了典型的“City has many Business”和“Business has many Post”之外,您还需要在 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();