問題描述
問題是查詢找不到specific_method(specific_method, specific_model,SpecificModel,specificMethod etc...),應(yīng)該與Laravel Eloquent中的WITH方法連接.任何想法如何解決它?我的代碼:
The problem is that the query can't find the specific_method(specific_method, specific_model,SpecificModel,specificMethod etc...), that should been joined with the method WITH from Laravel Eloquent. Any ideas how to solve it? My code:
//SpecificModel
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class SpecificModel extends Model {
protected $guard_name = 'web';
protected $table = 'SpecificTable';
protected $guarded = ['id'];
public function specificMethod(){
return $this->belongsTo('AppModelsAnotherModel','AnotherModel_id');
}
}
//AnotherModel
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class AnotherModel extends Model {
protected $guard_name = 'web';
protected $table = 'AnotherTable';
protected $guarded = ['id'];
}
//Query method
$model = app('AppModelsSpecificModel');
$query = $model::with('specificMethod:id,title');
$query = $query->orderBy('specific_method.title','desc');
return $query->get();
//Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'"specific_method.title"' in 'order clause' (SQL: select * from
`SpecificModel` where `SpecificModel`.`deleted_at` is null order by
`specific_method`.`title` desc)
推薦答案
發(fā)生這種情況是因?yàn)閎elongsTo 關(guān)系沒有像您期望的那樣執(zhí)行join
查詢(正如您從錯(cuò)誤中看到的得到).它執(zhí)行另一個(gè)查詢以獲取相關(guān)模型.因此,您將無法通過相關(guān)模型列訂購原始模型.
This happens because the belongsTo relationship does not execute a join
query as you expect it to (as you can see from the error you get). It executes another query to get the related model(s). As such you will not be able to order the original model by related models columns.
基本上,會(huì)發(fā)生 2 個(gè)查詢:
Basically, 2 queries happen:
使用
SELECT * from originalModel ...*
使用 SELECT * from relatedModel where in id (originalModelForeignKeys)
然后 Laravel 做了一些魔術(shù),將第二個(gè)查詢中的模型附加到第一個(gè)查詢中的正確模型上.
Then Laravel does some magic and attaches the models from the 2nd query to the correct models from the first query.
您需要執(zhí)行實(shí)際的join
能夠以您想要的方式訂購.
You will need to perform an actual join
to be able to order the way you want it to.
這篇關(guān)于如何在與 Laravel Eloquent 方法 WITH 連接的元素上使用 orderby的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!