I
I
Ilya Loopashko2021-09-08 07:15:02
Laravel
Ilya Loopashko, 2021-09-08 07:15:02

How to link 4 tables?

Kind Everyone. Faced with a problem. I have tables, in the controller there is an Index method
613838beb3894483287706.png

public function index(Request $request, ApiResponse $response)
    {
        $limit = $request->get('limit');
        if (!isset($limit)) $limit = 20;
        $orders = Order::with('equipments')->paginate($limit);
        if (count($orders) > 0) {
            $response->setStatus('OK');
            $response->setMessage('Данные успешно загружины');
            $response->setData(['orders' => $orders]);
        }
        return $response->asJson();
    }


There is a custom answer

class ApiResponse extends Response
{

    public $body = [
        'status' => 'ERROR',
        'message' => 'Произошла ошибка',
    ];

    public function setStatus($value) {
        $this->body['status'] = $value;
    }

    public function setMessage($value) {
        $this->body['message'] = $value;
    }

    public function setData($value) {
        $this->body['data'] = $value;
    }

    public function asJson()
    {
        return response()->json($this->body);
    }
}


Here is the response I get:

"data": {
    "orders": {
        "data": [
            "id": 1,
            "title": "Order 1",
            "equipments": [
            	{
            		"id": 1,
            		"title": 'Equipment 1'
            		"pivot": {
            			"wing_id": 1,
            		}
            	}
        ],
        ]
    }
}


How can I implement such a result

? I want to get it like this:

"data": {
    "orders": {
        "data": [
            "id": 1,
            "title": "Order 1",
            "equipments": [
            	{
            		"id": 1,
            		"title": 'Equipment 1'
            		"pivot": {
            			"wing": {
            				"id": 1
            				"title": Right
            			}


Model:
public function equipments()
    {
        return $this->belongsToMany(Equipment::class, 'equipment_order')->withPivot([
            'wing_id', 
        ]);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Myasnikov, 2021-09-18
@m9snikfeed

Everything is described in the documentation: https://laravel.com/docs/8.x/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question