简体   繁体   中英

Laravel hasMany relationship returning huge amounts of data which is not a collection?

I am working on a very simple API using laravel. Users have many tasks, and a task belongs to a user. My routes file is as follows :

<?php

Route::resource('users', 'UsersController');
Route::get('users/{user_id}/tasks', 'UsersController@show_tasks');
Route::resource('tasks', 'TasksController');

I want that the second route gets all the tasks related to that particular user. It is simple. I just added a relationship in my User model as follows :

public function tasks(){
        return $this->hasMany('Task');
    }

And the show_tasks method in my UsersController is as follows :

public function show_tasks($id){

    if(!$user = $this->user->find($id)){
        return Acme::response('error', 'Resource not found.', [], 404);
    }

    $tasks = $user->tasks();
    dd($tasks);

    return Acme::response('success', [], $tasks, 200);
}

I have placed the dd method because the response was returning an empty array and I wanted to see what is in the $tasks variable first hand. I thought it must be a collection object but when I ran this in my Postman REST client, it hanged due to the large data overflow I am assuming, screenshot below :

dd方法调用的输出!

If anyone is curious about the Acme::response method, I am also including that code :

public static function response($status = [], $messages = [], $data = [], $httpStatusCode){
        return Response::json([
            'status' => $status,
            'messages' => $messages,
            'data' => $data,
        ], $httpStatusCode);
    }

Why is the relationship not working? I have been this for hours and still can't figure out why! I am guessing I might be doing a very silly mistake somewhere but can't get to it anyway!

You shouldn't use () here. Instead of:

$tasks = $user->tasks();

you will get your tasks using:

$tasks = $user->tasks;

EDIT

When you have relation and you use $user->tasks it works as you would use $user->tasks()->get() so we can say it's a shortcut.

You could use parantheses you get relation you can add more conditions, for example you could do something like that:

$tasks = $user->tasks()->active()->get();

and define scope in your Task model:

function activeScope($q) {
  return $q->where('status',1);
}

And now you can get only active tasks for user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM