Laravel 5.1中的多层次关系

时间:2016-05-13 10:13:17

标签: laravel-5 laravel-5.1

我有三张桌子,我想在那之间建立多重关系 订单,ORDER_DETAILS,书

enter image description here

我想在一个数组之间建立一个共同的关系。我正在使用以下代码

Order.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public $timestamps = false;
    protected $table='orders';

    public function orderDetails(){
        return $this->hasMany('App\OrderDetail','order_id');
    }
}

OrderDetail.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrderDetail extends Model
{
    //
    public $timestamps = false;
    protected $table='order_details';

    public function orders(){
        return $this->belongsToMany('App\Order');
    }

    public function book(){
        return $this->hasMany('App\Book');
    }

}

Book.php

public function orderDetail(){
        return $this->hasManyThrough('App\OrderDetail','App\Book','id','item');
    }

其中item是book表中的外键和主键

OrderController.php

中的

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Order,App\OrderDetail,App\Book,App\User;
use Auth;
use App\Http\Requests;
use Response;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    public function userOrders(){OrderDetail::find($orderId)->where('order_id',$orderId)->where('item','book.id')->get(); }

0 个答案:

没有答案