I have a Laravel Model:
class Order extends Eloquent{
protected $table = 'orders';
public function orderItems(){
return $this->hasMany('OrderItem');
}
public static function findByUserMonthYear($user_id, $month, $year){
return Order::where('user_id', '=', $user_id)
->where('month', '=', $month)
->get();
// ->where('year', '=', $year);
}
}
And of course I have an OrderItem
class
class OrderItem extends Eloquent{ ...
But if I do:
$order = Order::findByUserMonthYear(Auth::user()->id, Date::getDate(), 2014);
$order->orderItems();
I get the following:
Call to undefined method Illuminate\Database\Eloquent\Collection::orderItems()
What am I doing wrong? If I were to change the statement to Order::with('orderItems')
the relationship seems to work fine, but I'd like to delete all the orderItems
associated to the current Order
.
Your ->get()
within you findByUserMonth is returning a Collection. If this query returns only one collection then use the ->first()
instead, but if your query returns multiple results then eager load the results of orderItems like so;
public static function findByUserMonthYear($user_id, $month, $year){
return self::with('orderItems')->where('user_id', '=', $user_id)
->where('month', '=', $month)
->get();
// ->where('user_id', '=', $year);
}
Then you can access the results like so;
@foreach($orders as $order)
{{$order->orderItem}}
@endforeach
This is because the return being a collection, so you have to loop through them. The use {{$order->orderItem}}
to access the results
Im not too sure on this but i think you can delete all the models within a hasMany like so; $order->orderItem()->delete();
as the return of orderItem()
is a Query\\Builder instance.
您的第二个类必须是扩展Order类,此行用于OrderItem类:
class OrderItem extends Order {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.