Reputation: 524
I have this model in laravel 6.0.4:
class CategoryModel extends Model
{
public function parent()
{
return $this->belongsTo(CategoryModel::class, 'parent_id');
}
public function children()
{
return $this->hasMany(CategoryModel::class, 'parent_id');
}
}
And the controller
class CategoryController extends Controller
{
public function index()
{
CategoryModel::with('children')->get(); // this is working
CategoryModel::with('parent')->get(); // this is not working
}
}
Here is the schema
Schema::create('category', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('parent_id')->nullable();
$table->string('name');
$table->index(['parent_id']);
$table
->foreign('parent_id')
->references('id')
->on('category')
->onDelete('set null')
->onUpdate('set null');
});
I can get the children but for parent, it returns an empty array for all the records.
Upvotes: 1
Views: 3054
Reputation: 524
I was selecting the columns like this
CategoryModel::select('id', 'name')->with('parent')->get();
I did not know that I also should select the parent_id. Now It's working fine with this
public function parent()
{
return $this->hasOne(CategoryModel::class, 'id', 'parent_id');
}
Upvotes: 0
Reputation: 93
Try this:
public function parent()
{
return $this->hasOne(CategoryModel::class, 'id', 'parent_id');
}
public function children()
{
return $this->hasMany(CategoryModel::class, 'parent_id', 'id');
}
Upvotes: 1
Reputation: 1270
You can use below code to make relationship with self class:
public function parent()
{
return $this->belongsTo('App\CategoryModel','parent_id')->where('parent_id',0)->with('parent') ;
}
public function children()
{
return $this->hasMany('App\CategoryModel','parent_id')->with('children');
}
Upvotes: 0