如何在与Laravel雄辩的方法WITH结合在一起的元素上使用orderby [英] How to use orderby on element that was joined with Laravel Eloquent method WITH

查看:535
本文介绍了如何在与Laravel雄辩的方法WITH结合在一起的元素上使用orderby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是查询无法找到应该与Laravel Eloquent的WITH方法结合的specific_method(specific_method,specific_model,SpecificModel,specificMethod等).有什么想法如何解决吗? 我的代码:

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)

推荐答案

之所以会发生这种情况,是因为belongsTo关系不会执行您期望的join查询(从错误中您可以看到).它执行另一个查询以获取相关模型.因此,您将无法通过相关模型列订购原始模型.

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.

基本上,会发生2个查询:

Basically, 2 queries happen:

  1. 使用SELECT * from originalModel ...*

使用SELECT * from relatedModel where in id (originalModelForeignKeys)

然后Laravel做一些魔术,将第二个查询的模型附加到第一个查询的正确模型.

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

您将需要执行实际的 join 才能订购您想要的方式.

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

这篇关于如何在与Laravel雄辩的方法WITH结合在一起的元素上使用orderby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆