【问题标题】:How can I group select values in a single select as array in laravel mysql?如何在 laravel mysql 中将单个选择中的选择值分组为数组?
【发布时间】: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


【解决方案1】:

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

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

第一步是建立关系;除了典型的“City有很多Business”和“Business有很多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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2023-03-20
    • 2016-07-08
    相关资源
    最近更新 更多