Laravel 关系:hasOne vs belongsToMany
Posted
技术标签:
【中文标题】Laravel 关系:hasOne vs belongsToMany【英文标题】:Laravel relationships: 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_types
(name
,item_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();
【问题讨论】:
你的人际关系错了。 ;) 【参考方案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');
编码愉快!
【讨论】:
顺便说一句,狗和主人的例子不是我的,它来自雷曼:inlehmansterms.net/2014/07/28/has_one-vs-belongs_to @hvpc 我编辑了删除“[已解决]”部分的问题标题,如果它真的对您有帮助,请接受答案。以上是关于Laravel 关系:hasOne vs belongsToMany的主要内容,如果未能解决你的问题,请参考以下文章
Laravel Lighthouse Graphql HasOne 嵌套关系不起作用
EF 核心一对多关系 HasOne().WithMany() vs HasMany().WithOne()
laravel one to on hasOne 关系手动外键和本地键检测错列