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.

推荐答案

好的,我已经重读了你的问题,我认为你有一些地方错了,所以我不想在主要帖子上留下任何进一步的 comments ,我想我可以试着回答一下,所以就这样吧.

First off, your relationship is the wrong type and the wrong way around. As I understand it (and as I implement these things in my own work) a product belongs to a brand - a brand may have multiple products, but a product can only have one brand. So first your DB schema - you mention you have a products table with the normal columns and then the foreign key brand_id. So far so good: this is consistent with the way I interpret the relationship.

然而,你接着向我们展示你的模型.你的产品型号是hasOne品牌,但实际上它属于一个品牌.你也不需要定义关系的反面——你需要双方共同努力才能让Laravel很好地工作.除此之外,你的命名有点不正常——它可能会起作用,但如果我们遵循拉威尔的惯例,我们会得到以下结果:

In the products model: 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');
    }
}

好的,到目前为止一切都很好.您会注意到各种约定:

  1. Table names are plural (products, brands)
  2. 外键使用单数(brand_id)
  3. Model names are singular and StudlyCase (so Product for a table products, Brand for table brands)
  4. 只要遵循Laravel约定(即表名是模型类名的复数Snake_Case版本),就不必指定$table属性
  5. 你应该以两种方式定义关系(每个模型中一个,belongsTo的倒数是hasMany,还有hasOne/belongsTobelongsToMany/belongsToMany对)
  6. 检索关系的方法的名称是合理的-如果您期望一个结果,则将其设为单数(Product中为brand),如果您希望多个结果中为复数(Brand中为products),则将其设为单数
  7. Use the model classnames in your relationship definitions ($this->hasMany('Brand') not $this->hasMany('brands') or any other variation

如果你坚持这些规则,你的模型可以非常简洁,但非常强大.

Now, as for how you actually define real data, I have a feeling the code you posted may work fine (it really depends on how clever Laravel is behind the scenes), but as I suggested in my first comment, I'd ensure that I saved the $brand before calling associate(), just so that Laravel doesn't get lost working out what to do. As such I'd go for:

// 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(),因为它会自动获取$brandid值,将其放入$productbrand_id字段,然后保存$product.

有关更多信息,请参阅有关如何处理此关系的文档插入:http://laravel.com/docs/eloquent#one-to-many

Anyway, hopefully this post clears up a good amount of what was wrong with your code. As I said above, these are conventions, and you can go against them, but to do so you have to start putting extra code in, and it can be quite unreadable for other developers. I say if you pick a given framework, you may as well follow its conventions.

Laravel相关问答推荐

laravel错误更新使用外键的数据库

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

我应该如何使用遵循依赖反转原则的工厂方法设计模式

Laravel 语法 GroupBy 获取列到数组

使用Laravel Blade Formatter和PHP Intelephense进行 VSCode 格式化

Laravel created_at 返回对象代替数据库中的日期格式?

Laravel:转义LIKE子句?

Laravel 控制器中一种特定方法的中间件

将 Laravel MYSQL 更改为 utf8mb4 以在现有数据库中支持表情符号

如何在使用 Laravel 在控制器中发送邮件之前更改邮件配置?

Laravel Electron邮件验证模板位置

PHP 5.5,什么情况下PHP会导致很高的committed memory

在 Laravel Eloquent 中,limit 与 take 有什么区别?

如何在 Laravel Eloquent 中 Select 某些字段?

Laravel:自定义或扩展通知 - 数据库模型

Laravel Mix 生成字体到另一个目录

在 Laravel 5.4 中向多个抄送收件人发送Electron邮件

Laravel 搜索关系

Laravel Eloquent模型如何从关系表中获取数据

如何在 Laravel 中动态更改 .env 文件中的变量?