Reputation: 175
Im trying to access url property on files table by $post->file->url
, but i'm getting "Trying to get property of non-object" error. My table and model is different because i can't use File
as model name. is there something missing? I hope someone come with solution. here's my tables:
- posts:
[PK] id
title
[FK] featured_image
- files:
[PK] id
title
url
my model:
class TheFile extends \Eloquent
{
protected $table = 'files';
public function post() {
return $this->belongsTo('Post');
}
}
class Post extends \Eloquent
{
protected $table = 'posts';
public function file() {
return $this->hasOne('TheFile', 'id', 'featured_image');
}
}
thanks in advance.
Upvotes: 0
Views: 4276
Reputation: 175
I changed my table name to medias, and my model to Media. Then put these code into Post
model . It's works. The name of tables, model and method must be similar.
public function media() {
return $this->belongsTo('Media', 'featured_image', 'id');
}
Upvotes: 2
Reputation: 14212
Maybe I'm wrong but as I see it, you actually have the relationship the wrong way around here. If table X
has one table Y
then the FK field is on Y
and related to the PK on X
. But you have it the other way around.
As such you need to do one of two things:
Change your database to put post_id
on files
rather than having featured_image
(points as file`.`id
) on posts
Change your relationships to match your database structure:
class TheFile extends \Eloquent
{
protected $table = 'files';
public function post() {
return $this->hasOne('Post');
}
}
class Post extends \Eloquent
{
protected $table = 'posts';
public function file() {
return $this->belongsTo('TheFile');
}
}
Obviously with your various field changes too if you aren't going to change the tables.
The basic rule of thumb is that if a table has the FK it's the 'belongs to' table. The other table is either 'has one' or 'has many'. The slight exception to this rule is obviously 'belongs to many' where a table can relate to another table where neither has an FK - but even that's a specialised version of the same rule - X
'has many' X_Ys
and Y
'has many' X_Ys
and X_Y
belongs to X
and X_Y
belongs to Y
. So it's just syntactic sugar really.
Upvotes: 2