我有一个User
表,需要允许用户有一个父用户.
the table would have the fields:
-
id
-
parent_id
-
email
password
我如何在Eloquent 的ORM中定义这种自引用关系?
我有一个User
表,需要允许用户有一个父用户.
the table would have the fields:
id
parent_id
email
password
我如何在Eloquent 的ORM中定义这种自引用关系?
I had some success like this, using your exact DB table.
User Model:
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
public function parent()
{
return $this->belongsTo('User', 'parent_id');
}
public function children()
{
return $this->hasMany('User', 'parent_id');
}
}
and then I could use it in my code like this:
$user = User::find($id);
$parent = $user->parent()->first();
$children = $user->children()->get();
Give that a try and let me know how you get on!