Assume we have two db tables: posts
and threads
:
threads
id - integer
title - string
posts
id - integer
body - text
created_at - timestamp
thread_id - integer (fk)
and two Eloquent models:
class Post extends Model {
public function thread()
{
return $this->hasOne('App\Thread');
}
}
class Thread extends Post {
protected $table = 'threads';
public function post()
{
return $this->belongsTo('App\Post');
}
}
What I want to achieve is Thread
object having id, title, body, created_at
attributes, while Post
object having id, body, created_at
attributes.
Yet, I still get error:
Column not found: 1054 Unknown column 'body' in 'field list'
which is MySQL error that basically means that Laravel's trying to look up the body
column in the threads
table. However, it is stored in the posts
table.
What you are trying to do is unnecessary with Eloquent.
The data that is retreived from the database iss storred in the $attributes
property.
So unless you are sharing any behaviour you don't need to inherit from anything other than Model
.
OK, so here is my updated answer after some research on your question. As you have defined table schema ie
threads
id - integer
title - string
posts
id - integer
body - text
created_at - timestamp
thread_id - integer (fk)
This means Thread
has many or just one (depends on relation) Post
, and Post
belongs to Thread
, so the relationship would be something like this
class Thread extends Model{
protected $table = 'threads';
public function post()
{
return $this->hasMany('App\Post');//Or hasOne('App\Post')
}
}
class Post extends Model {
public function thread()
{
return $this->belongsTo('App\Thread');
}
}
What you want to achieve is Thread
object having id, title, body, created_at
attributes, while Post
object having id, body, created_at
attributes.
Now according to current scene, One Thread
, may have more than one Post
. Here you'll always get body
and created_at
in relationship for object Thread
e,g Thread::with('post')->get();
, and vice versa
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.