laravel 5.1关系的问题

时间:2016-06-16 09:02:31

标签: laravel laravel-5 laravel-5.1

我有3个名为Order - factor - products的表 为了我有跟踪代码。在因素i中有product_id和order_id。 我该如何购买订购产品? :|

例如:order:where('trackingCode','HashCode')->ProductsInFactore()->get();

订单:

Schema::create('order', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('family');
        $table->string('email');
        $table->string('phone');
        $table->string('state');
        $table->string('city');
        $table->string('address');
        $table->string('PostalCode');
        $table->boolean('status')->default(0);
        $table->string('TrackingCode');
        $table->timestamps();
    });

Factore:

 Schema::create('factor', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('count');
        $table->integer('order_id')->unsigned();
        $table->integer('product_id')->unsigned();
        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('order_id')->references('id')->on('order')->onDelete('cascade');
        $table->timestamps();
    });

和产品

Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->longText('content');
        $table->string('colors');
        $table->tinyInteger('rate');
        $table->string('price');
        $table->string('discount')->default(0);
        $table->string('image');
        $table->string('url');
        $table->integer('category_id')->unsigned();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->timestamps();
    });

订单型号

public function products()
{
    return $this->hasManyThrough('App\products', 'App\factor','order_id','id','product_id');
}

控制器

$order = order::find(23)->products;
dd($order);

1 个答案:

答案 0 :(得分:0)

如果您将模型中的关系定义为“有很多通过”关系(请参阅laravel docs),那么您可以这样做

$order = Order::find($id);
$products = $order->products;

获取属于特定订单的所有产品。

相关问题