How I make my query in laravel to a table with self relationship. And i need he return a query category and subcategory as json format, for exemple:
['room':{
bed room:1,
kid room:2,
},
'living room ':{
sitting-room:3
}][1]
Migration the tale:
public function up() {
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('subcategories_id')->unsigned()->nullable();
$table->foreign('subcategories_id')
->references('id')
->on('categories');
// ->onDelete('cascade');
});
}
I think your proper solution would be
Category Model
class Cateogry extends Model {
public function subCategory(){
return $this->hasMany('\App\SubCategory');
}
}
SubCategory Model
<?php
class SubCategory extends Model {
public function Category(){
return $this->belongsTo('\App\Category');
}
}
In your controller
SomeController
<?php
class SomeController extends Controller {
public function index(){
return Category::with('subCategory')->get()
}
}
Output
[
{
name: 'Category1'
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00'
subcategory: [
{
subcategory_name: 'subcategory1',
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00'
},
{
subcategory_name: 'subcategory2',
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00'
}
],
},
{
name: 'Category1'
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00',
subcategory: [],
}
]
Hope this helps.
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.