gpt4 book ai didi

php - Laravel leftJoin 只加入右表的最后一条记录

转载 作者:行者123 更新时间:2023-11-30 22:16:32 26 4
gpt4 key购买 nike

我是 laravel 的新手。

我有两张 table 。1)产品2) 价格

-----------------------------
- products -
-----------------------------
- id_product | int (p_key) -
- name | varchar -
-----------------------------

-------------------------
- prices -
-----------------------------
- id_price | int (p_key) -
- id_product | int -
- price | int -
-----------------------------

products 表包含有关产品的数据,例如 idname、...价格变化存储在 prices 表中,其中最后一条记录是应向用户显示的最新价格。

现在我想搜索 products 并从 prices 表中获取每个产品的最新价格。这是我的查询:

$result = DB::table('products')->leftJoin('prices', function($join) {
$join->on('products.id_product', '=', 'prices.id_product');
})->whereRaw(MY_SEARCH_FILTERS);

上面的代码是错误的,因为如果一个产品在prices表中有4条记录,那么它会在$result中重复4次,但只有1条记录与应显示最后价格。

最佳答案

这里我们有 2 个表 usersanswers,其中 users 是左表,answers 是右表有用户答案。

我们想将 usersanswers 左连接,但连接应该与最新记录或 answers 表相连接。

$query = Users::select('users.id', 'users.user_name','answers.created_at as last_activity_date')
->leftJoin('answers', function($query)
{
$query->on('users.id','=','answers.user_id')
->whereRaw('answers.id IN (select MAX(a2.id) from answers as a2 join users as u2 on u2.id = a2.user_id group by u2.id)');
})
->where('users.role_type_id', Users::STUDENT_ROLE_TYPE)->get();

关于php - Laravel leftJoin 只加入右表的最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38093970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com