laravel:雄辩示例将数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21814049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:44:25  来源:igfitidea点击:

laravel: eloquent example insert data to database

modelinsertlaravelprimary-keyeloquent

提问by Klaas

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.

我很抱歉问这个问题,但我来自 codeIgniter 并且很难理解雄辩的模型插入。这对我来说是一种处理模型的新方式。

i have read this articleand understand some basics now.

我已经阅读了这篇文章,现在了解了一些基础知识。

I have the following example. I have a product which has many attributes but the relevant one is brand and product name. (see the following example tables)

我有以下示例。我有一个产品有很多属性,但相关的是品牌和产品名称。(请参阅以下示例表)

products: id(PK),name,description,brand_id brands: id(PK),name

产品:id(PK),name,description,brand_id 品牌:id(PK),name

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

简而言之。我想要 products.brand_id 中的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.

为了更清楚。我有2个模型。产品和品牌型号。但是,我不清楚模型中应该包含什么。这是我当前的产品模型。我认为品牌模型只应该有一个受保护的 $table = "brands"; 模型类中的行。

 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.

有人可以向我解释我做错了什么。我找不到一个好的教程如何在具有关系的雄辩模型中插入数据。大多数教程都是关于显示数据的。

回答by alexrussell

Okay, I've re-read your question and I think you have a few things wrong, so rather than leaving any further comments on the main post I figured I could have a go at an answer, so here goes.

好的,我已经重新阅读了你的问题,我认为你有一些问题,所以与其在主要帖子上留下任何进一步的评论,我想我可以尝试一下答案,所以这里是。

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 productstable 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.

首先,你们的关系是错误的类型和错误的方式。据我了解(以及在我自己的工作中实现这些东西时),一个产品属于一个品牌——一个品牌可能有多个产品,但一个产品只能有一个品牌。所以首先你的数据库模式 - 你提到你有一个products包含普通列的表,然后是外键brand_id。到目前为止一切顺利:这与我解释这种关系的方式一致。

However, you then go on to show us your model. You have the Product model as hasOneBrand - but actually it belongs to a brand. You also don't define the inverse of the relationship - you need both sides to make Laravel work well. In addition to that your naming is a bit out of whack - it'll possibly work, but if we follow Laravel conventions we get the following:

但是,然后您继续向我们展示您的模型。您将产品模型作为hasOne品牌 - 但实际上它属于一个品牌。您也没有定义关系的倒数 - 您需要双方才能使 Laravel 正常工作。除此之外,您的命名有点不正常 - 它可能会起作用,但是如果我们遵循 Laravel 约定,我们会得到以下内容:

In the productsmodel: Product.php

products模型中:Product.php

class Product extends Eloquent
{
    public function brand()
    {
        return $this->belongsTo('Brand');
    }
}

Now the brandsmodel: Brand.php

现在brands模型:Brand.php

class Brand extends Eloquent
{
    public function products()
    {
        return $this->hasMany('Product');
    }
}

Okay so far so good. You'll notice various conventions:

好的到目前为止一切顺利。您会注意到各种约定:

  1. Table names are plural (products, brands)
  2. Foreign keys use the singular (brand_id)
  3. Model names are singular and StudlyCase (so Productfor a table products, Brandfor table brands)
  4. The $tableproperty doesn't have to be specified as long as you follow Laravel conventions (i.e. table name is the plural snake_case version of the model classname
  5. You should define the relationship both ways (one in each model, belongsTo's inverse is hasMany, there's also the pairs hasOne/belongsToand belongsToMany/belongsToMany)
  6. The names of the methods to retrieve the relationship are sensible - if you expect one result, make it singular (brandin Product), if you expect multiple results make it plural (productsin Brand)
  7. Use the model classnames in your relationship definitions ($this->hasMany('Brand')not $this->hasMany('brands')or any other variation
  1. 表名是复数 ( products, brands)
  2. 外键使用单数 ( brand_id)
  3. 模型名称是单数和 StudlyCase(所以Product对于 table productsBrand对于 table brands
  4. $table属性没有被指定,只要你遵循Laravel约定(即表名是模型类名的复数snake_case版本
  5. 您应该以两种方式定义关系(每个模型中都有一个,belongsTo相反的是hasMany,还有对hasOne/belongsTobelongsToMany/ belongsToMany
  6. 检索关系的方法的名称是合理的 - 如果您希望得到一个结果,则将其设为单数 ( brandin Product),如果您希望有多个结果,则将其设为复数 ( productsin Brand)
  7. 在关系定义中使用模型类名($this->hasMany('Brand')不是$this->hasMany('brands')或任何其他变体

If you stick to these rules, your models can be really concise but very powerful.

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

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 $brandbefore calling associate(), just so that Laravel doesn't get lost working out what to do. As such I'd go for:

现在,至于您如何实际定义真实数据,我觉得您发布的代码可能会正常工作(这实际上取决于 Laravel 在幕后的聪明程度),但正如我在第一条评论中所建议的那样,我会确保我保存了$brandbefore 调用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();

This way, you know you have the brand in the database with its IDs already defined before you go and use it in a relationship.

这样,您就知道在数据库中已有品牌,并且在您开始在关系中使用它之前已经定义了其 ID。

You can also define the relationship in the opposite manner, and it may be less brain-hurting to do so:

你也可以用相反的方式定义关系,这样做可能不那么伤脑筋:

// 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);

You don't need to call save()on either model after that last line, as it wil automatically take the $brand's idvalue, place it into the $product's brand_idfield, and then save the $product.

您不需要save()在最后一行之后调用任一模型,因为它会自动获取$brand'sid值,将其放入$product'sbrand_id字段,然后保存$product.

For more information see the docs on how to do this relationship inserting: http://laravel.com/docs/eloquent#one-to-many

有关更多信息,请参阅有关如何插入此关系的文档: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.

无论如何,希望这篇文章可以清除大量代码的问题。正如我上面所说,这些都是约定,您可以反对它们,但要这样做,您必须开始添加额外的代码,而其他开发人员可能很难理解。我说如果你选择一个给定的框架,你也可以遵循它的约定。