laravel:雄辩示例将数据插入数据库 [英] laravel: eloquent example insert data to database

查看:23
本文介绍了laravel:雄辩示例将数据插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

i have read this article and 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)

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

products: id(PK),name,description,brand_id brands: 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.

简而言之.我想要 products.brand_id 中的brand.id

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

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

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.

推荐答案

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

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.

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

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.

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

However, you then go on to show us your model. You have the Product model as hasOne Brand - 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:

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');
    }
}

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

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

  1. 表格名称是复数形式(productsbrands)
  2. 外键使用单数 (brand_id)
  3. 型号名称是单数和 StudlyCase(所以 Product 用于表 productsBrand 用于表 brands)
  4. $table 属性不必指定,只要你遵循 Laravel 约定(即表名是模型类名的复数蛇形版本
  5. 您应该以两种方式定义关系(每个模型中一个,belongsTo 的逆是 hasMany,还有对 hasOne/belongsTobelongsToMany/belongsToMany)
  6. 检索关系的方法的名称是合理的 - 如果您希望得到一个结果,请将其设为单数(Product 中的 brand),如果您希望获得多个结果它是复数(products in Brand)
  7. 在关系定义中使用模型类名($this->hasMany('Brand') 而不是 $this->hasMany('brands') 或任何其他变化
  1. Table names are plural (products, brands)
  2. Foreign keys use the singular (brand_id)
  3. Model names are singular and StudlyCase (so Product for a table products, Brand for table brands)
  4. The $table property 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/belongsTo and belongsToMany/belongsToMany)
  6. The names of the methods to retrieve the relationship are sensible - if you expect one result, make it singular (brand in Product), if you expect multiple results make it plural (products in Brand)
  7. Use the model classnames in your relationship definitions ($this->hasMany('Brand') not $this->hasMany('brands') or any other variation

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

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

现在,至于您如何实际定义真实数据,我感觉您发布的代码可能工作正常(这实际上取决于 Laravel 在幕后的聪明程度),但正如我在第一条评论中所建议的那样,我'd 确保我在调用 associate() 之前保存了 $brand,这样 Laravel 就不会迷失在想做什么的时候.因此,我会去:

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.

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.

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

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

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

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

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

For more information see the docs on how to do this relationship inserting: 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:雄辩示例将数据插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆