Vis*_*air 4 php laravel eloquent laravel-4
我正在使用PHP Laravel Framework.我有1到M个关系表order和products.
ORDER TABLE - orderid <--autoincrement primary key
- orderdate
- Name
PRODUCTS TABLE - productid <--autoincrement primary key
- orderid <--foreign key reference to order table
- productName
- price
我的型号如下 - >
订购型号:
class Order extends Eloquent
{
protected $table = 'order';
public function products()
{
return $this->hasMany('Products','orderid');
}
}
Run Code Online (Sandbox Code Playgroud)
产品型号:
class Products extends Eloquent
{
protected $table = 'products';
}
Run Code Online (Sandbox Code Playgroud)
我有一个表格,我在订单日期,客户名称和产品详细信息可以是多个产品.用户可以在一个订单中有一个或多个产品.
所以现在我必须一次性插入两个表的详细信息.
我读了这篇文档http://laravel.com/docs/eloquent#inserting-related-models
他们给出了以下代码来插入相关模型 - >
$comments = array(
new Comment(array('message' => 'A new comment.')),
new Comment(array('message' => 'Another comment.')),
new Comment(array('message' => 'The latest comment.'))
);
$post = Post::find(1);
$post->comments()->saveMany($comments);
Run Code Online (Sandbox Code Playgroud)
但是在这里他们知道要从父表中查找的id,但在我的情况下,我必须在Order表中插入详细信息,然后在Products表中插入有关之前插入的订单的详细信息.问题是如何找到新插入的orderid?我orderid在Order表中使用autoincrement作为字段.
只是:
$order = new Order;
... // assign some properties
$order->save();
$products = [new Product(...), new Product(...)];
$order->products()->saveMany($products);
Run Code Online (Sandbox Code Playgroud)
protected $primaryKey像Zwacky已经说过的那样设置模型.
现在,我怀疑这是你想要的关系.这意味着每个产品仅存在于单个订单的上下文中.我认为这应该是很多人,但那是你的号召.