1

I have 3 model, and I already set Relation.

Model A:

namespace App\Model;
use Illuminate\Database\Eloquent\Model;

class ComponentA extends Model
{
    protected $table = 'ComponentA';
    protected $primaryKey = 'ComponentAId';

    public function ComponentB() {
        return $this->hasOne(
            'App\Model\ComponentB', 'ComponentBId', 'ComponentBId'
        );
}

Model B:

namespace App\Model;
use Illuminate\Database\Eloquent\Model;

class ComponentB extends Model
{
    protected $table = 'ComponentB';
    protected $primaryKey = 'ComponentBId';

    public function ComponentC() {
        return $this->hasOne(
            'App\Model\ComponentC', 'ComponentCId', 'ComponentCId'
        )->withDefault();
    }
}

Model C:

namespace App\Model;
use Illuminate\Database\Eloquent\Model;

class ComponentC extends Model
{
    protected $table = 'ComponentC';
    protected $primaryKey = 'ComponentCId';
}

Now, in the controller, I want to call C from A and sort by C column, I use with() method.

Controller:

$this->ComponentA->with(['ComponentB.ComponentC' => function($query) {
    $query->orderby('ComponentCId','DESC');
}])->paginate();

That is correct, no any error, but the result doesn't sort.

Please help me that where I am wrong ?

Thanks a lot.

Ignacio
  • 11
  • 2
  • 1
    Possible duplicate of [laravel eloquent sort by relationship](https://stackoverflow.com/questions/40837690/laravel-eloquent-sort-by-relationship) – Pankaj Mar 06 '19 at 06:08
  • Your sub-query is sorted... and that's not what you're trying to do. You can see what I mean if you change the final ->get() to ->toSql() – Tarek Adam Mar 06 '19 at 06:25
  • You can sort via the Collection or you can change your sql builder to a join instead of an eager loader. – Tarek Adam Mar 06 '19 at 06:27
  • @TarekAdam Thank you for your answer, I am edit the part of Controller, Because I want to use Laravel paginate, so I can't use Collection and have any method except join ? – Ignacio Mar 06 '19 at 06:49
  • You can access the paginator as needed. https://stackoverflow.com/questions/45022316/how-do-i-paginate-a-collection-or-custom-query-into-api-json-in-laravel/45022317#45022317 – Tarek Adam Mar 06 '19 at 06:56
  • That pagination link I send uses Illuminate\Support\Collection so you may need to change it to Illuminate\Database\Collection or something. Just keep that in mind if you try the code I linked you to. – Tarek Adam Mar 06 '19 at 07:03

0 Answers0