thinkphp6 LEFT JOIN有重复数据
如果在使用ThinkPHP6的LEFT JOIN时出现重复数据问题,有以下几种解决方法:
- 使用DISTINCT关键字去重
在SQL语句中使用DISTINCT关键字去除重复数据,例如:
$data = Db::table('table1')
->field('t1.*, t2.name')
->alias('t1')
->leftJoin('table2 t2', 't2.id = t1.table2_id')
->distinct(true)
->select();
- 使用GROUP BY关键字分组去重
在SQL语句中使用GROUP BY关键字分组去重,例如:
$data = Db::table('table1')
->field('t1.*, t2.name')
->alias('t1')
->leftJoin('table2 t2', 't2.id = t1.table2_id')
->group('t1.id')
->select();
- 在模型中定义关联关系,使用关联查询
在模型中定义关联关系,例如:
class Table1 extends Model
{
public function table2()
{
return $this->belongsTo(Table2::class);
}
}
class Table2 extends Model
{
public function table1s()
{
return $this->hasMany(Table1::class);
}
}
然后在控制器中,使用关联查询,例如:
$data = Table1::with('table2')->select();
``
原文地址: https://www.cveoy.top/t/topic/f0B7 著作权归作者所有。请勿转载和采集!