很抱歉问这个问题,但我来自 codeIgniter,很难理解 Eloquent 模型插入。对我来说,这是一种处理模型的新方法。
我已阅读 this article现在了解一些基础知识。
我有以下示例。我有一个产品有很多属性,但相关的是品牌和产品名称。 (请参阅以下示例表)
产品:id(PK)、名称、描述、brand_id
品牌:id(PK),名称
现在问题来了。我知道我可以创建一个新品牌,我知道我可以如何创建一个新产品。但是我不知道如何将两者连接在一起。这是我现在拥有的一些代码。我想创建一个新产品并自动填充品牌表。这是 Controller 的一部分。
简而言之。我想要 products.brand_id 里面的brands.id
$product = new Products;
$product->name = "product1";
$product->description = "description1";
$brand = new Brands;
$brand->name = "brand1"
$product->brand()->associate($brand);
$brand->save();
$product->save();
为了更清楚。我有2个模型。产品和品牌型号。但是,我不清楚模型中应该包含什么。这是我当前的产品模型。我认为 Brands 模型只应该有一个 protected $table = "brands";模型类内的行。
class Products extends Eloquent {
protected $table = 'products';
public function brand()
{
return $this->hasOne('brands');
}
}
有人可以向我解释我做错了什么。我找不到一个很好的教程如何在具有关系的 Eloquent 模型中插入数据。大多数教程都是关于显示数据的。
最佳答案
好的,我已经重新阅读了你的问题,我认为你有一些问题,所以与其在主要帖子上留下任何进一步的评论,我想我可以尝试一个答案,所以就这样吧。
首先,你们的关系是错误的类型和错误的方式。据我了解(以及在我自己的工作中实现这些东西),产品属于一个品牌——一个品牌可能有多个产品,但一个产品只能有一个品牌。因此,首先是您的数据库架构 - 您提到您有一个 products
表,其中包含普通列,然后是外键 brand_id
。到目前为止一切顺利:这与我解释这种关系的方式是一致的。
但是,您接着向我们展示您的模型。您的产品型号为 hasOne
品牌 - 但实际上它属于一个品牌。你也没有定义关系的反面——你需要双方来让 Laravel 正常工作。除此之外,您的命名有点不正常——它可能会起作用,但如果我们遵循 Laravel 约定,我们会得到以下结果:
在 products
模型中:Product.php
class Product extends Eloquent
{
public function brand()
{
return $this->belongsTo('Brand');
}
}
现在是
brands
模型:Brand.php
class Brand extends Eloquent
{
public function products()
{
return $this->hasMany('Product');
}
}
好的,到目前为止一切都很好。您会注意到各种约定:
products
、brands
)brand_id
) Product
用于表 products
,Brand
用于表 brands
)$table
属性(即表名是模型类名 belongsTo
的逆是 hasMany
,还有对 hasOne
/belongsTo
和 belongsToMany
/belongsToMany
)brand
中的 Product
),如果您希望有多个结果,请将其设为复数(products
中的 Brand
) $this->hasMany('Brand')
而不是 $this->hasMany('brands')
或任何其他变体 如果你坚持这些规则,你的模型可以非常简洁但非常强大。
现在,至于您如何实际定义真实数据,我感觉您发布的代码可能工作正常(这实际上取决于 Laravel 在幕后的聪明程度),但正如我在第一条评论中建议的那样,我会确保我在调用
$brand
之前保存了 associate()
,这样 Laravel 就不会迷失在做什么。因此,我会去:// create new brand and save it
$brand = new Brand;
$brand->name = "Brand 1";
$brand->save();
// create new product and save it
$product = new Product;
$product->name = "Product 1";
$product->description = "Description 1";
$product->brand()->associate($brand);
$product->save();
这样,您就知道数据库中有品牌,并且在您在关系中使用它之前已经定义了它的 ID。
你也可以用相反的方式定义关系,这样做可能不会那么伤脑筋:
// create new product and save it
$product = new Product;
$product->name = "Product 1";
$product->description = "Description 1";
$product->save();
// create new brand and save it
$brand = new Brand;
$brand->name = "Brand 1";
$brand->save();
// now add the product to the brand's list of products it owns
$brand->products()->save($product);
您无需在最后一行之后在任一模型上调用
save()
,因为它会自动获取 $brand
的 id
值,将其放入 $product
的 brand_id
字段,然后保存 $product
。有关详细信息,请参阅有关如何插入此关系的文档:http://laravel.com/docs/eloquent#one-to-many
无论如何,希望这篇文章能澄清你的代码有很多问题。正如我上面所说,这些是约定,您可以违反它们,但要这样做,您必须开始添加额外的代码,这对于其他开发人员来说可能非常难以阅读。我说如果你选择一个给定的框架,你不妨遵循它的约定。
关于model - laravel: Eloquent 例子将数据插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21814049/