【问题标题】:Laravel 5.4 How to responses JSON with Relationship?Laravel 5.4 如何用关系响应 JSON?
【发布时间】:2018-01-14 09:03:00
【问题描述】:

我想用 Laravel 响应 JSON,我有 CategoryModel 属于 SongModel。

这是我的类别模型

class CategoryModel extends Model
{
    protected $table = 'categories';
    protected $fillable = [
        'id',
        'name',
    ];

    public function song()
    {
        return $this->hasMany(SongModel::class);
    }
}

这是我的 SongModel

class SongModel extends Model
{
    protected $table = 'songs';
    protected $fillable = [
        'id',
        'name',
        'url',
        'categories_id',
        'singers_id',
        'types_id',
    ];

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

我想用关系响应 JSON。我写道:

class SongController extends Controller
{
    public function index(SongModel $songModel)
    {
        $song = $songModel->category()->get();
        return response()->json(["DATA" => $song], 201);
    }
}

【问题讨论】:

    标签: php json laravel laravel-5 laravel-5.4


    【解决方案1】:

    ,你可以使用with('song')

    lass SongController extends Controller
    {
        public function index(SongModel $songModel)
        {
            $song = $songModel::with('song')->get();
            return response()->json(["DATA" => $song], 201);
        }
    }
    

    【讨论】:

    • 非常感谢您的回答:D
    【解决方案2】:

    试试这个。 return response()->json(["DATA" => $songModel->load('category')->toArray()], 201);

    【讨论】:

    • 它显示我是这样的:{ "DATA": { "category": null } }
    • @Vichit 哦,我明白了。也许您的控制器中的$songModel 为null,因此它在响应中返回null。
    • 我认为您的路由模型绑定代码定义不正确。
    • @ImPerat0R_2 那么,我该怎么办?
    • 这是我的路线。 Route::resource('/api/v1/songs', 'SongController', ['only' => ['index', 'show',]]);
    【解决方案3】:

    为此,您只需在返回响应之前加载关系:

    public function index(SongModel $songModel)
    {
        $songModel->load('category');
    
        return response()->json(["DATA" => $songModel], 201);
    }
    

    https://laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading

    希望这会有所帮助!

    【讨论】:

    • 它向我显示了 Null 类别。 {"DATA":{"category":null}}
    • @Vichit 抱歉,我不是打算将负载分配给song。我已经更新了我的答案。
    • 比如我想这样回复 { "DATA": [ { "id": 3, "name": 再见, "url": "...... " "category_id": 2, "category": { "id": 2, "name": "....", } } ] }
    • @Vichit 您是否更新了我编辑的两个部分,即您应该返回$songModel 而不是$song
    • @Vichit 这回答了你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-22
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2021-03-23
    相关资源
    最近更新 更多