wenus wenus - 1 month ago 8
PHP Question

Laravel eloquent from DB

I have a very complicated db query, but I would like to know or is a possibility to short it and make it easier by eloquent?
My Model and his db is :

class Order extends Model
{
public $timestamps = false;
public $incrementing = false;

public function products()
{
return $this->hasMany(OrderProducts::class);
}

public function statuses()
{
return $this->belongsToMany(OrderStatusNames::class, 'order_statuses', 'order_id', 'status_id');
}

public function actualKioskOrders()
{
return
$rows = DB::select("SELECT o.id, o.number, o.name client_name, o.phone,
o.email, o.created_at order_date, osn.name actual_status
FROM orders o
JOIN order_statuses os ON os.order_id = o.id
JOIN (SELECT o.id id, MAX(os.created_at) last_status_date FROM orders o
JOIN order_statuses os ON os.order_id = o.id GROUP BY o.id) t
ON t.id = os.order_id AND t.last_status_date = os.created_at
JOIN order_status_names osn ON osn.id = os.status_id
WHERE os.status_id != 3");
}

}

Answer Source

Of course you can. Laravel query builder implements everything you need.

See Laravel Docs: Query Builder, it have join methods, where clause methods and select methods.

You can do for example the following:

Order::select(['id','number', 'name', 'client_name'])
->where('status_id', '!=', 3)
->join('order_statuses', 'order_statuses.order_id, '=', 'orders.id')
->get()

That's just an example on how you can create queries. Chain many methods that you need to create your query, the docs show many ways to do it, including with more complex joins if you need.