Reputation: 1155
I have 2 tables with quite complex relationships. Table users
has two foreign keys to table images
and table images
has one foreign key to table users
which is unrelated to other two foreign keys.
I can't make correctly models. I need so that all referenced fields are associated with models and also so that there is images
property in User
which returns all images owned by that user.
Here is my table generating code:
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');
});
And here is my try with models:
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');
}
}
I thought that code above should work, however all properties return strings not objects.
Upvotes: 1
Views: 59
Reputation: 153140
You can't name the relationships the same as the name of your foreign key columns!
Changing either one should work, however I suggest you change the foreign key columns to owner_id
, portrait_id
etc... Then you also don't need to specify the foreign key column in your relation since you're using the conventional names.
Upvotes: 2