【发布时间】:2015-01-15 16:22:07
【问题描述】:
我有 2 个关系非常复杂的表。表users 有两个表images 的外键,表images 有一个表users 的外键,它与其他两个外键无关。
我无法制作正确的模型。我需要让所有引用的字段都与模型相关联,并且User 中有images 属性,它返回该用户拥有的所有图像。
这是我的表格生成代码:
Schema::create('users', function ($table) {
$table->increments('id')->unsigned();
$table->integer('portrait')->unsigned()->nullable();
$table->integer('backimg')->unsigned()->nullable();
$table->timestamps();
});
Schema::create('images', function ($table) {
$table->increments('id')->unsigned();
$table->integer('owner')->unsigned();
$table->foreign('owner')->references('id')->on('users');
$table->timestamps();
});
Schema::table('users', function($table) {
$table->foreign('portrait')->references('id')->on('images');
$table->foreign('backimg')->references('id')->on('images');
});
这是我对模型的尝试:
class User extends Eloquent implements UserInterface, RemindableInterface {
public function backimg(){
return $this->hasOne('Image', 'backimg');
}
public function portrait(){
return $this->hasOne('Image', 'portrait');
}
public function images(){
return $this->belongsTo('Image', 'owner');
}
}
class Image extends Eloquent {
public function owner(){
return $this->hasOne('User', 'owner');
}
}
我认为上面的代码应该可以工作,但是所有属性都返回字符串而不是对象。
【问题讨论】:
-
旁注:
->nullable()->default(null)是多余的,你不需要那里的默认值。 -
@TimLewis 我知道,我写它是为了以后很容易改成其他东西。