【发布时间】:2016-01-09 04:31:10
【问题描述】:
我正在尝试在最新构建的 laravel-homestead 上使用 Laravel 5 在同一类的两个实例之间创建一对多的关系。但是,由于某种原因,laravel 没有将任何关系保存到持久性中。
这是我的 eloquent-model 类:
class Page extends Model
{
//relationship
public function subpages()
{
return $this->hasMany('Ordiweb\Page','motherpage','pagename');
}
public function motherpage()
{
return $this->belongsTo('Ordiweb\Page','motherpage','pagename');
}
//table-name
protected $table = 'pages';
protected $primaryKey = 'pagename';
protected $timestamps = false;
//fillable attributes
protected $fillable = ['pagename','pagetitle','pagecontent','boxcontent'];
}
所以一个页面可以是 0..n 个子页面的母页面。母页和子页都是 Page-class 的实例。
我不完全确定 belongsTo() 和 hasMany() 中的 foreignKey ('motherpage') 和 localKey ('pagename') 参数,但 laravel 文档并没有真正解释它们是如何使用的。但是,当我运行迁移时,我没有收到任何错误,所以我猜它是正确的。
这是我对应的迁移类:
class CreatePagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->string('pagename');
$table->string('motherpage')->nullable();
$table->string('pagetitle')->nullable();
$table->text('content')->nullable();
$table->text('boxContent')->nullable();
$table->primary('pagename');
$table->foreign('motherpage')->references('pagename')->on('pages')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('pages');
}
}
这是我的分页播种器:
class PageTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('pages')->delete();
$page = new Page();
$page->pagename = 'testpage';
$page->pagetitle = 'Testpage Title';
$page->content = '<h3>Hello</h3>';
$page->save();
$page2 = new Page();
$page2->pagename = 'testpage2';
$page2->pagetitle = 'Testpage2 Title';
$page2->content = '<h3>Hello 2</h3>';
$page2->boxcontent = 'Test in the box.';
$page2->save();
$page->subpages()->save($page2);
$page2->motherpage()->associate($page);
$page->save();
$page2->save();
}
}
如您所见,我试图通过两种方式定义关系。
- 通过 ->subpages()->save($page2); 设置 hasMany;
- 通过 ->motherpage()->associate($page); 设置 reverse-hasMany;
运行时:“artisan migrate:refresh --seed”一切似乎工作正常,没有出现错误消息。除了关系数据之外,所有定义的具有属性的模型都保存到持久性中。只有关系字段保持为空。
如图所示,“testpage2”的母页字段应该是“testpage”而不是 NULL
我真的不知道从这里开始做什么。一切似乎都设置正确,我在哪里搞砸了?
【问题讨论】:
-
我认为一个页面应该属于许多子页面。试试这个:
public function subpages() { return $this->hasMany('Ordiweb\Page','motherpage','pagename'); } -
嗯?我的 subpages() 有什么不同?
-
我的错。我的意思是将 hasMany 更改为 belongsToMany。
-
这也行不通。 :( 但我不得不说,自从 laravel 文档本身声明使用 belongsTo() 来表示反向一对多关系时,我会感到惊讶。见这里:laravel.com/docs/5.1/eloquent-relationships#one-to-many
-
更改为 belongsToMany 后尝试删除 '$page2->save();'在调用'$page->subpages()->save($page2);'之前在你的播种机中。
标签: php laravel eloquent one-to-many laravel-artisan