【问题标题】:Laravel subquery (select) in DB:RawDB:Raw 中的 Laravel 子查询(选择)
【发布时间】:2020-08-16 13:01:32
【问题描述】:

我正在尝试显示用户最喜欢的文章 我想为每篇文章添加收藏夹的用户数量

我尝试使用此代码:

$result = $result->join('favorite_clothes', 'favorite_clothes.clothe_id', '=', 'clothes.id');
$result = $result->Where('favorite_clothes.user_id', '=', Auth::user()->id);
$result = $result
->groupBy('clothes.id')
->get(["clothes.id", DB::raw("count(favorite_clothes.id) as favorite_count"), "clothes.name"])
->toArray();

但在这种情况下,favorite_count 始终为一 (1)。 我想我可以使用DB:raw() 中的子查询来解决它,比如

DB::raw("SELECT count(favorite_clothes.id) as favorite_count from favorite_clothes where favorite_clothes.clothe_id = clothes.id")

但这不起作用。 还有其他方法吗? 谢谢。

【问题讨论】:

    标签: mysql sql laravel join group-by


    【解决方案1】:

    我希望每篇文章都有多少用户将其放入收藏夹

    我认为你想要:

    select clothe_id , count(*) no_users
    from favorite_clothes
    group by clothe_id 
    

    如果你想显示衣服的名字而不是它的id,那么:

    select c.name, count(*) no_users
    from favorite_clothes fc
    inner join clothes c on c.id = fc.clothe_id
    group by fc.clothe_id, c.name
    

    【讨论】:

    • 我有一个可以解决问题的查询,但我正在寻找一种方法将其放入上面的 laravel 代码中。 SELECT count(favorite_clothes.id) as favorite_count from favorite_clothes where favorite_clothes.clothe_id = clothes.id
    • @Nourein:这不是有效的 SQL(作为初学者,没有 from 子句)。我不能告诉你如何将我的查询翻译成 lavarel - 但是你应该能够将它作为原始查询运行。
    • 错字,已修改。但仍然无法正常工作,因为DB:raw() 不接受子查询。
    【解决方案2】:

    如果您的模型有关系:

    $user = User::find(1);
    
    foreach($user->favoriteClothes As $favoriteClothe)
    {
     $numberOfFavoriteWithSameClothe = $favoriteClothe->users->count();
    }
    

    短查询更新

    User::find(1)->with(['favoriteClothes' => function ($q) {
        $q->withCount('users');
    }])->find();
    

    【讨论】:

    • 这是一个解决方案,但我试图在一个查询中完成所有事情,你知道复杂性、执行时间......等等。
    • 这对你有帮助吗?
    【解决方案3】:

    我喜欢一个解决方案,我必须加入同一张桌子两次。
    first:只获取当前用户最喜欢的产品,
    second:to获取将其放入收藏夹的用户。

    $result = $result->join('favorite_clothes', 'favorite_clothes.clothe_id', '=', 'clothes.id');
    $result = $result->join('favorite_clothes as fc_for_count', 'favorite_clothes.clothe_id', '=', 'clothes.id');
    $result = $result->Where('favorite_clothes.user_id', '=', Auth::user()->id);
    $result = $result->groupBy('clothes.id')
                     ->get(["clothes.id", DB::raw("count(fc_for_count.id) as favorite_count"), "clothes.name"])
                     ->toArray();
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多