我想將一個原始的SQL查詢轉換爲Eloquent,所以我也可以附加一些渴望加載的模型,所以我不必編輯一些我得到的模板。問題是,查詢得到了一些子查詢,我不知道如何將查詢轉換成Eloquent的格式。有問題的查詢是:需要將MySQL查詢轉換爲Eloquent;從哪裏開始/如何思考?
SELECT
e_eh.id,
s.name as serie,
s.id as serie_id,
e_eh.season,
e_eh.episode,
e_eh.name,
eh1.prog_trans,
eh1.prog_check,
eh1.prog_sync,
eh1.avi
FROM (
SELECT
e.*
, (
SELECT
eh.id
FROM episode_histories AS eh
WHERE 1
AND eh.episode_id = e.id
ORDER BY
eh.id DESC
LIMIT 1
) AS eh_id
FROM episodes AS e
WHERE 1
AND e.completed = 0
AND e.deleted_at IS NULL
) AS e_eh
INNER JOIN episode_histories AS eh1 ON e_eh.eh_id = eh1.id
INNER JOIN series as s ON s.id = e_eh.serie_id
ORDER BY prog_trans DESC, prog_check DESC, prog_sync DESC
我已經嘗試了幾件事,但都沒有工作。我有點卡在如何把這個想法變成Laravel/Eloquent。來自Laravel本身的文檔也沒有太大的幫助。
簡而言之: 我有兩個模型,一個是情節,另一個是episode_histories,它存儲了一些關於相關情節的歷史。第三個模型是展示模型,它的相關展示。我需要得到一個情節,與相關的演出模型(已經是我的模型中的關係)。但我也需要爲給定的情節獲取最新的episode_histories模型。
我目前在我的模型是什麼:
插曲: `類集擴展模型 { 使用SoftDeletes; 使用App \ History; //歷史模型
protected $table = 'episodes';
protected $primaryKey = 'id';
public $timestamps = true;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/* Eloquent relations */
public function show() {
return $this->belongsTo('App\Serie', 'serie_id', 'id');
}
public function history() {
return $this->hasMany('App\History', 'episode_id', 'id')->orderBy('id', 'desc');
}
public static function getEpisodes2() {
return DB::select();
}
} And my history model looks like this:
類歷史擴展型號 { 使用SoftDeletes;
protected $table = 'episode_histories';
protected $primaryKey = 'id';
public $timestamps = true;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/* Eloquent relations */
public function episode() {
return $this->belongsTo('App\Episode');
}
public function user() {
return $this->belongsTo('App\User', 'user_id', 'id');
}
/* Custom functions */
}` 我希望有人能幫我解決這個問題。如果信息丟失,請告訴我,所以我可以補充一點。
如果查詢生成器還可以返回相關的模型(預先加載),那麼我敢肯定,我可以看看它。 – CptChaos