Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottenere categorie e sottocategorie Query Builder in Laravel

Andrei con modelli eloquenti

class Category extends Model
{
    protected $table = 'tbl_form'; // 'posts'

    public function posts()
    {
        return $this->hasMany(Post::class, 'category', 'category')->select(['title']);
    }
}
class Post extends Model
{
    protected $table = 'tbl_form'; // 'posts'

    public function category()
    {
        return $this->belongsTo(Category::class, 'category', 'category');
    }
}

E recuperalo così:

$categories = Category::all();
dd($categories[0]->posts);