How to use orderby on element that was joined with Laravel Eloquent method WITH

本秂侑毒 提交于 2019-12-31 05:13:11

问题


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 App\Models;
use Illuminate\Database\Eloquent\Model;

class SpecificModel extends Model {

    protected $guard_name = 'web';
    protected $table = 'SpecificTable';
    protected $guarded = ['id'];

    public function specificMethod(){
        return $this->belongsTo('App\Models\AnotherModel','AnotherModel_id');
    }
}


//AnotherModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class AnotherModel extends Model {

    protected $guard_name = 'web';
    protected $table = 'AnotherTable';
    protected $guarded = ['id'];
}

//Query method
$model = app('App\Models\SpecificModel');
$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)

回答1:


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.

Basically, 2 queries happen:

  1. Fetch the original model with SELECT * from originalModel ...*

  2. Fetch the related models with SELECT * from relatedModel where in id (originalModelForeignKeys)

Then Laravel does some magic and attaches the models from the 2nd query to the correct models from the first query.

You will need to perform an actual join to be able to order the way you want it to.



来源:https://stackoverflow.com/questions/49212466/how-to-use-orderby-on-element-that-was-joined-with-laravel-eloquent-method-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!