【发布时间】:2020-01-19 02:38:19
【问题描述】:
我有这个用于 MySQL 的 SQL 查询,它运行良好。但是我需要使用查询生成器重写它,并且需要完全避免DB::raw(),因为开发数据库与生产数据库不同。我知道远非理想,但不幸的是它就是这样。
SELECT athletes.*,
(
SELECT performance
FROM performances
WHERE athletes.id = performances.athlete_id AND performances.event_id = 1
ORDER BY performance DESC
LIMIT 0,1
) AS personal_best
FROM athletes
ORDER BY personal_best DESC
Limit 0, 100
我正在努力如何重写personal_best 部分。我有运动员的成绩表,我只需要选择每个运动员的最佳成绩作为他的个人最好成绩。
我试图搜索答案,但我找到的所有答案都包括原始添加原始 SQL。
任何想法或提示将不胜感激。
提前谢谢你!
所以我接受了我可能不得不为此使用 Eloquent,但仍然无法取得进展。这是我的代码:
class Athlete extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'athletes';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* Get the performances for the Athelete post.
*
* @return HasMany
*/
public function performances()
{
return $this->hasMany('App\EloquentModels\Performance', 'athlete_id');
}
}
class Performance extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'performances';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
}
【问题讨论】:
标签: mysql laravel laravel-query-builder