Laravel Eloquent关联模型查询设置查询条件与指定字段和无限分类

Models



namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Cat extends Model
{

    protected $table = 'cat';
    

    public function child() {
        return $this->hasMany('App\Models\Cat', 'parent_id', 'id');
    }

    public function allChildren()
    {
        return $this->child()->with(['allChildren' => function($query) {
            $query->select('id', 'parent_id', 'name');
        }]);
    }
}

Controller调用

$categories = cat::with(['allChildren' => function($query) {
            $query->select('id', 'parent_id', 'name');
        }])->select('id', 'parent_id', 'name')->get();

结果

{
            "id": 1,
            "name": "一级分类",
            "parent_id": 0,
            "all_children": [
                {
                    "id": 2,
                    "parent_id": 1,
                    "name": "二级分类1",
                    "all_children": []
                },
                {
                    "id": 3,
                    "parent_id": 1,
                    "name": "二级分类2",
                    "all_children": [
                    	{
                            "id": 4,
                            "parent_id": 3,
                            "name": "三级分类",
                            "all_children": []
                        }
                	]
                },
         	]
        },

你可能感兴趣的:(laravel,php)