Laravel 5.4如何回应JSON与关系?

时间:2017-08-07 06:13:16

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

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

这是我的CategoryModel

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);
    }
}

3 个答案:

答案 0 :(得分:2)

要执行此操作,您只需在返回响应之前加载关系:

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

希望这有帮助!

答案 1 :(得分:1)

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

答案 2 :(得分:0)

OR ,您可以使用with('song')

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