I am sorry to ask this but I come from codeIgniter and have a really hard time understanding eloquent model insertion. This is a new way of working with models for me.
我已经读了this article本书,了解了一些基本知识.
我有下面的例子.我有一个产品,它有很多属性,但相关的是品牌和产品名称.(请参阅以下示例表)
产品:id(主键),名称,描述,brand_id 品牌:ID(主键),名称
Now here comes the problem. I know i can create a new brand and I know how I can create a new product. However I have no qlue how to connect the two together. Here is some code I have right now. I want to create a new product and automatically fill the brand table. This is a part of the controller right now.
In short. I want the brands.id inside the products.brand_id
$product = new Products;
$product->name = "product1";
$product->description = "description1";
$brand = new Brands;
$brand->name = "brand1"
$product->brand()->associate($brand);
$brand->save();
$product->save();
To make it more clear. I have 2 models. products and brands models. However it is not clear to me what should be in the model. This is my Current products model. I think the brands model only should have a protected $table = "brands"; line inside the model class.
class Products extends Eloquent {
protected $table = 'products';
public function brand()
{
return $this->hasOne('brands');
}
}
Can somebody explain to me what i do wrong. I cannot find a good tutorial how to work with inserting data inside eloquent models with relationships. The most tutorials are about displaying data.