Laravel一对多关系-对不存在字段的引用 [英] Laravel one-to-many relationship - a reference to a non-existent field

查看:69
本文介绍了Laravel一对多关系-对不存在字段的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在拉瓦雷尔(Lavarel)进行迁移时,我忘了什么呢?展示我想要获得的是我要向用户分配他的订单并订购他订购的产品.因此,我有一个User表,Order表和OrderProduct表.与Order表具有一对多关系的Usera表,与OrderProduct表具有一对多关系的Order表.从关系Order和OrderProduct开始,我得到一个错误:

What do I forget about doing migrations in Lavarel that once relations act to me like this and once so? Presenting what I want to get is I want to assign the user his order and order the products he ordered. So I have a User table, the Order table, and the OrderProduct table. Usera table with one-to-many relation with the Order table, Order table with one-to-many relation with the OrderProduct table. Starting from the relation Order and OrderProduct, I get an error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'order_products_tables.order_table_id' in 'where clause' (SQL: select * from `order_products_tables` where `order_products_tables`.`order_table_id` = 1 and `order_products_tables`.`order_table_id` is not null)

此错误清楚地表明他无法在order_products_tables表中找到order_table_id列,这听起来很愚蠢,因为没有这样的字段,但是有一个order_id字段,并且在迁移过程中使用哪个字段是关系,我不明白为什么Laravel尝试引用order_products_tables.

And this error says clearly and clearly that he can not find the order_table_id column in the order_products_tables table and I am not surprised what it may sound silly because there is no such field but there is an order_id field and in migrations is described with which field is the relationship and I can not understand why Laravel tries refer to order_products_tables.

迁移顺序:

Schema::create('order_tables', function (Blueprint $table) {
    $table->increments('id');

    $table->integer('user_id')->unsigned()->nullable();

    $table->foreign('user_id')
        ->references('id')
        ->on('users');

    $table->timestamps();
});

迁移OrderProduct:

Migrations OrderProduct:

Schema::create('order_products_tables', function (Blueprint $table) {
    $table->increments('id');

    $table->integer('order_id')->unsigned();

    $table->integer('count')->unsigned();
    $table->integer('price')->unsigned();

    $table->foreign('order_id')
        ->references('id')
        ->on('order_tables');

    $table->timestamps();
});

由于迁移而产生的结果,order_products_tables表存储了order_tables表中的记录ID,并且关系基于该ID.

As it results from the migration, the order_products_tables table stores the record ID from the order_tables table and the relationship is based on that ID.

模型订单表:

class OrderTable extends Model
{
    protected $table = 'order_tables';

    public function user()
    {
        return $this->belongsTo(User::class, 'id');
    }

    public function products()
    {
        return $this->hasMany('App\OrderProductTable');
    }
}

Model OrderProduct表:

Model OrderProduct table:

class OrderProductTable extends Model
{
    protected $table = 'order_products_tables';

    public function order()
    {
        return $this->belongsTo(OrderTable::class, 'id');
    }
}

我不明白为什么要对order_table_id进行引用.我已经按照相同的原则完成了其他关系,例如,用户和订单,并且可以正常工作,突然间我遇到了这种情况.我应该在哪里寻找解决方案,为什么呢?

I do not understand why the reference to order_table_id is going. I have done other relations, eg User and Order on the same principle, and it works without a problem, suddenly here I have such a case. Where should I look for a solution and why does it wo

推荐答案

此错误来自使用错误表名,或者,更正确地说,是未正确定义关系.以下关系定义将解决您的问题:

This error comes from using wrong table names or, to be more correct, not defining the relationship correctly. The following relationship definitions will fix your issue:

class OrderTable extends Model
{
    protected $table = 'order_tables';

    public function products()
    {
        return $this->hasMany('App\OrderProductTable', 'order_id', 'id');
    }
}

class OrderProductTable extends Model
{
    protected $table = 'order_products_tables';

    public function order()
    {
        return $this->belongsTo(OrderTable::class, 'order_id', 'id');
    }
}

您先前的代码不起作用的原因是Laravel使用默认值,这些默认值基本上是假设,并且要求您的数据库遵循某些命名约定.这是您应遵循的约定列表*:

The reason your previous code did not work is that Laravel uses default values which are basically assumptions and require your database to follow certain naming conventions. Here is a list of conventions you should follow*:

  • 表应以模型名称和复数形式(snake_case)命名:
    • 模型User应该具有一个名为users的表.
    • 模型Category应该有一个名为categories的表(请参见英文复数形式).
    • 模型AccountManager应该具有一个名为account_managers的表.
    • Tables should be named after the model name in plural form and snake_case:
      • Model User is supposed to have a table named users.
      • Model Category is supposed to have a table named categories (see the english plural).
      • Model AccountManager is supposed to have a table named account_managers.
      • 如果存在模型CategoryProduct(具有表categoriesproducts)并且它们之间存在多对多关系(belongsToMany()),则数据透视表的表为应该被称为order_product(而不是product_order,因为o在字母表中的p之前).
      • If there are models Category and Product (with tables categories and products) and there is a many-to-many relationship (belongsToMany()) between them, the table for the pivot table is expected to be called order_product (and not product_order because o comes before p in the alphabet).
      • 例如,当引用BlogPost模型上的User模型时,Laravel期望user_id列作为BlogPost模型上的外键. User模型上引用的主键来自$primaryKey属性,默认情况下为'id'.
      • When referencing the User model on a BlogPost model for example, Laravel expects a user_id column as foreign key on the BlogPost model. The referenced primary key on the User model is taken from the $primaryKey property, which is 'id' by default.

      对于您的特定情况,这意味着我们希望使用以下模型,表和列:

      For your particular scenario, this means we would expect the following models, tables and columns:

      • 具有表users和列的模型User,类似于Laravel的默认迁移.
      • 具有表orders和列iduser_idcreated_at,...
      • 的列的Order模型
      • 具有表products和列idnameprice,...
      • 的列的Product模型
      • 具有表order_products和列idorder_idproduct_idquantity,...
      • 的列的OrderProduct模型
      • Model User with table users and columns like in the default migration of Laravel.
      • Model Order with table orders and columns like id, user_id, created_at, ...
      • Model Product with table products and columns like id, name, price, ...
      • Model OrderProduct with table order_products and columns like id, order_id, product_id, quantity, ...

      理论上,模型OrderProduct不是必需的.通过在Order模型上定义$this->belongsToMany(Product::class)->withPivot('quantity')和在Product模型上定义$this->belongsToMany(Order::class)->withPivot('quantity')(请注意枢轴字段),您也应该能够在没有该系统的情况下构建相同的系统.就个人而言,我更喜欢用于多对多关系的额外模型.

      In theory, the model OrderProduct is not necessary. You should also be able to build the same system without it by defining $this->belongsToMany(Product::class)->withPivot('quantity') on the Order model and $this->belongsToMany(Order::class)->withPivot('quantity') on the Product model (note the pivot fields). Personally, I prefer extra models for many-to-many relations though.

      要参考雄辩的关系,请参阅文档中的 .当需要覆盖关系的默认表名或列名时,将提供所有关系类型的示例以及其他参数的附加信息.

      For reference to Eloquent relationships, have a look at the documentation. There are examples for all relationship types and additional information for the additional parameters when you need to override the default table or column names for your relations.

      *此列表可能缺少重要信息.它是尽力而为.

      这篇关于Laravel一对多关系-对不存在字段的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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