I want to get a relation, here is my code:
OrderController.php
public function orders()
{
$orders = Order::with('packages')->OrderBy('created_at', 'DESC')->paginate();
return view('admin/orders/orders')->with(compact('orders'));
}
Order.php
function packages(){
return $this->hasMany('App\Models\Package', 'id','cart_items');
}
but the problem is cart_items
contains a value like this (5,6) comma separated, how can I get relation hasMany from array?
CodePudding user response:
Its's not possible by ORM need to work with mutator and accessor. Please remove packages method and try this in your Order model;
protected $appends = ['packages'];
public function getPackagesAttribute ()
{
if ($this->cart_items) {
$cart_items = explode(',', $this->cart_items);
if(count($cart_items)>0) {
return Package::whereIn('id', $cart_items)->get();
}
} return null;
}