简体   繁体   中英

Cant get proper data in Controller Laravel belongsToMany Relation - Laravel / Eloquent

A user(employer) have many posts and many user(employee) can apply these posts. Point is employer should get which users applied for each its posts.

I tried $employees = Post::find(//anyNumber//)->people; it gives proper applicants infos but it should be dynamic for each employer user.

Tables..

applies   ->  | users_id(employee) | posts_id |
posts     ->  | id                 | user_id(employer)  | (other posts cols ... )
user_info ->  | id                 | (name col  etc... for employee)

Post Model..

public function people()
{
   return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}

Controller..

public function index()
{
    $user_id = Auth::id();
    $myPosts = Post::where('user_id',$user_id)->get();
    $employees = Post::find(//anyNumber//)->people; // this line

    dd($employees);
}

If I understand the question correctly, you are looking for all the employees who applied for the post of the employer. You should be able to pull all those "People" in the same query you get your posts from using the "with" statement.

For example:

$myPosts = Post::where('user_id', $user->id)->with('people')->get();

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