0👍
✅
This could be achieved by a number of ways.
SOLUTION 1:
The easiest that I can think of could be create a relationship on the Category
model like:
class Category extends Model
{
protected $table = 'Category';
protected $primaryKey = 'category_id';
public function parent()
{
return $this->belongsTo(static::class, 'parent_id', 'category_id')
}
}
Then from the controller:
use App\Category;
class CategoriesController extends Controller
{
public function index()
{
return Category::with('parent')->get();
}
}
Then your JSON response will be something like:
[
{
category_id,
parent_id,
category_name,
parent: {
category_id,
parent_id,
category_name,
}
},
{
category_id,
parent_id,
category_name,
parent: {
category_id,
parent_id,
category_name,
}
}
]
// from the front-end you can access the parent name by:
category.parent.category_name
SOLUTION 2:
A more performant approach can be adding a subquery like this:
class CategoriesController extends Controller
{
public function index()
{
Category::addSelect('parent_name' => DB::table('category as parent'))
->select('parent.category_name')
->whereColumn('parent.category_id', 'category.category_id')
->limit(1)
}->get();
}
Then your JSON response will be something like:
[
{
category_id,
parent_id,
category_name,
parent_name
},
{
category_id,
parent_id,
category_name,
parent_name
}
]
Source:stackexchange.com