【问题标题】:Laravel relationships: hasOne vs belongsToManyLaravel 关系:hasOne vs belongsToMany
【发布时间】:2015-12-12 05:16:47
【问题描述】:

我有 3 张桌子:

   Schema::create('item_types', function (Blueprint $table) {
        $table->increments('id')->unsignet();
        $table->string('name')->unique();
    });

    Schema::create('items', function (Blueprint $table) {
        $table->increments('id')->unsignet();
        $table->string('name');
        $table->text('description');
        $table->string('photo');
        $table->integer('item_type_id')->unsignet(); //->nullable();
        $table->integer('brand_id')->unsignet(); //->nullable();
        $table->float('price')->unsignet();
        $table->timestamps();
    });

    Schema::create('brands', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name');
        $table->string('logo');
        $table->text('description');
    });

需要它们之间的关系...

所以我设置:

hasOne for item_types and brands in Item.php 

belongsToMany for Items in ItemType.php and Brand.php

尝试了很多组合 知道这很愚蠢,但什么也做不了)

当我像这样填写表格时:

factory(App\Item::class, 5)->create()->each(function($i) {
        $i->type()->save(factory(App\ItemType::class)->make());
        $i->brand()->save(factory(App\Brand::class)->make());
}

出现错误:

未找到列:1054 “字段列表”中的未知列“item_type_id” (SQL:插入item_typesnameitem_type_id)值(等, 1))

如果我在 Item.php 中设置:

`hasOne('App\ItemType', 'id', 'item_type_id');`

品牌也一样

所有表都填满了,但 items 表中的 item_type_id 和 brand_id 为空

[已解决]

下面回答+

factory(App\Item::class, 50)->create()->each(function($i) {
    $i->ItemType()
        ->associate(factory(App\ItemType::class)
        ->create());
    $i->brand()
        ->associate(factory(App\Brand::class)
        ->create());
    $i->save();

【问题讨论】:

  • 你的人际关系错了。 ;)

标签: laravel activerecord orm eloquent one-to-many


【解决方案1】:

你的人际关系错了。永远记住狗和主人的插图:

[...] 假设我们有一个 Dog 模型和一个 Owner 模型。我们可以立即说所有者has_one狗和狗belongs_to所有者。

在您的特定情况下,您的狗是 Item,它们的所有者是 ItemType 和 Brand:

# Item.php

public function itemType()
{
    return $this->belongsTo('App\ItemType');
}

public function brand()
{
    return $this->belongsTo('App\Brand');
}

还有其他两个类:

# ItemType.php

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

# Brand.php

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

编码愉快!

【讨论】:

猜你喜欢
  • 2020-03-04
  • 2020-10-06
  • 2015-02-22
  • 2018-05-19
  • 2018-05-29
  • 2017-04-21
  • 2016-03-17
  • 2018-03-08
  • 2021-03-22
相关资源
最近更新 更多