我用oneToMany关系创建了两个模型Text和TextMain(texts_main.text_id = texts.id)
Text.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Text extends Model{
use SoftDeletes;
protected $table = 'texts';
protected $fillable = [
'text',
'lang_id'
];
protected $dates = [
'deleted_at'
];
}
TextMain.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TextMain extends Model{
protected $table = 'texts_main';
protected $fillable = [
'user_id',
'text_id'
];
public $timestamps = false;
public function texts() {
return $this->hasMany('App\Models\Text', 'id', 'text_id');
}
}
然后我定义了两个工厂
$factory->define(App\Models\Text::class, function (Faker\Generator $faker) {
return [
'text' => $faker->paragraph,
'lang_id' => 1
];
});
$factory->define(App\Models\TextMain::class, function (Faker\Generator $faker) {
return [
'user_id' => 1
];
});
在我的播种器php文件中
public function run()
{
factory(TextMain::class, 5)->create()
->each(function($tm) {
$tm->texts()
->save(factory(Text::class)->make());
});
}
但是当我开始在表格“texts_main”字段中进行迁移和播种时,关系“text_id”等于0。
如何更改代码以解决此问题? 在此先感谢:)
UPD:
Schema::create('texts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->softDeletes();
$table->longText('text');
$table->integer('lang_id');
});
Schema::create('texts_main', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('text_id');
});