我有两个模型Status和StatusCategory,它们具有belongsToMany关系。我有一个数据透视表status_status_category,其中包含两个字段status_id和status_category_id我还将这两个字段作为主键。
我为Status和StatusCategoryModel创建了模型工厂。当我为它们播种时,我在终端输出中得到以下异常:
异常:此集合实例上不存在Property [id]。
相关代码如下:
$factory->define(App\Status::class, function (Faker $faker) {
return [
'name' => $faker->word
];
});
$factory->define(App\StatusCategory::class, function (Faker $faker) {
return [
'name' => $faker->word
];
});
public function statuses() {
return $this->belongsToMany( Status::class );
}
public function statusCategories() {
return $this->belongsToMany( StatusCategory::class );
}
factory( Status::class, 30 )->create()->each( function ( $u ) {
$u->statusCategories()->save( factory( StatusCategory::class )->make() );
} );
如果有人可以提供帮助,我不知道在哪里转到这里说实话。感谢
答案 0 :(得分:0)
您可以创建pivot
模型以种子pivot
表。这是一个例子:
状态模式
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Status extends Model{
protected $table='statuses';
protected $fillable = [
'something you want to fill'
];
public function statusStatusCategories(){
return $this->belongsToMany(StatusCategory::class);
}
}
StatusCategory模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class StatusCategory extends Model{
protected $table='status_categories';
protected $fillable = [
'something you want to fill'
];
public function statuses(){
return $this->belongsToMany(Status::class);
}
}
适用于pivot
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class StatusStatusCategory extends Pivot
{
protected $table='status_status_category';
protected $fillable = [
'status_id','status_category_id'
];
public function status(){
return $this->hasOne(Status::class, 'id', 'status_id');
}
public function statuscategory(){
return $this->hasOne(StatusCategory::class, 'id', 'statuscategory_id');
}
}
希望这有帮助。