简体   繁体   中英

Laravel Eloquent hasMany returning only one result?

So my Client model has a hasMany relationship with the Project model, because every client in the client table is associated with many projects in the projects table.

The method looks like this:

Client.php:

public function projects()
{
    return $this->hasMany('App\Projects', 'id', 'project_id');
}

Seems pretty straightforward. But when I try this from a controller:

$projects = Client::find(1)->projects()->get()

I get only a single result, the FIRST result, from the Project model, when there should be about a half dozen. This even happens if I change the integer sent to find().

So Eloquent is returning on the first row of the projects table every time. Why is it doing this and/or how can I get all of the relevant results?

A hasMany (or one-to-many ) relationship is defined in the Laravel Documentation as

A "one-to-many" relationship is used to define relationships where a single model owns any amount of other models.

In this case Many simply means one or more.


I assume that every project has a client_id reference. In that case changing your projects() function to

return $this->hasMany('App\Projects', 'client_id');

should work for you.

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