Laravel 拉维关系:有一对有一
我有三张桌子:Laravel 拉维关系:有一对有一,laravel,activerecord,orm,eloquent,one-to-many,Laravel,Activerecord,Orm,Eloquent,One To Many,我有三张桌子: Schema::create('item_types', function (Blueprint $table) { $table->increments('id')->unsignet(); $table->string('name')->unique(); }); Schema::create('items', function (Blueprint $table) { $tabl
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未知列“项类型id”
(SQL:在项目类型
(名称
,项目类型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();
你的关系不对劲。务必记住狗和主人的说明: […]假设我们有一个狗模型和一个主人模型。我们马上可以说主人有一只狗,而狗属于主人 在您的特殊情况下,您的狗就是物品,其主人是物品类型和品牌:
# 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');
}
快乐编码 你的关系处于错误的一方顺便说一句,狗和主人的例子不是我的,它来自雷曼:@hvpc我编辑了问题的标题,删除了“[已解决]”部分,如果答案真的对你有帮助,就接受它。