0

client Model

 protected $table = 'client';
    protected $fillable = [
        'client_name',
        'supplier_id'
    ];

 public function supplier()
    {
        return $this->belongsTo(Supplier::class, 'supplier_id', 'id');
    }

Supplier table

id    | supplier
1     | john 
2     | ace
3     | bravo

ClientController

$Client = new Client();
        $Client = $Client ->with(
            'supplier'
        );
 $Client = $Client->orderBy('supplier', 'DESC');
       

Error

Column not found: 1054 Unknown column 'supplier' in 'order clause' (SQL: select * from `client` order by `supplier` desc limit 20 offset 0)

i need to order by supplier from with relationship

3 Answers3

0

Depending on your laravel version you can try:

$Client = new Client();
return $Client ->with([
    'supplier' => function ($q){
    $q->orderBy('supplier');
    }
]);
Kevin Sada
  • 69
  • 4
0

If you want to order the supplier inside the Client, see this.

If you want to order the Client based on its supplier, see this.

rifqy abdl
  • 156
  • 1
  • 8
0

So, From what I have understood is that you want to orderBy your data based on a relationship's column.

If so, I am not sure if it's easy to do this with Eloquent. Though you can use Query Build as following:

$clientQuery = Client::query();

$clientQuery->selectRaw("clients.*, (SELECT MAX(created_at) from suppliers WHERE clients.supplier_id=suppliers.id) as orderBySupplier")
        ->orderBy("orderBySupplier", "DESC");
Hesan Naveed
  • 199
  • 5