Alb
Alb

Reputation: 37

Eloquent is setting a value to null

i'm having an error with Eloquent (and Many to Many relationship). This is my code:

$user = new Users;
$rs = $user
    ->company()
    ->where('company_role.users_id', $request->session()->get('usrid'))
    ->where('code', $request->company)
    ->first();

The query that Eloquent perform is this one:

select `companies`.*, `company_role`.`users_id` as `pivot_users_id`, `company_role`.`companies_id` as `pivot_companies_id`, `company_role`.`role_name` as `pivot_role_name` from `companies` inner join `company_role` on `companies`.`id` = `company_role`.`companies_id` where `company_role`.`users_id` is null and `company_role`.`users_id` = 1 and `code` = 12345678901 limit 1)"

How is this possible? Do you guys have any idea?

This is my Users model:

class Users extends Model
{
    //table associated with model
    protected $table = 'users';
    protected $primaryKey = 'id';

    public function company(){
        return $this->belongsToMany('App\Companies','company_role')->withPivot('role_name');
    }
}

Upvotes: 0

Views: 70

Answers (2)

Alb
Alb

Reputation: 37

It was a rookie error

i just changed this:

    $rs = $user->company()->where('company_role.users_id',$request->session()->get('usrid'))->where('code',$request->company)->first();

into this:

        $rs = $user->find($request->session()->get('usrid'))->company()->where('piva',$request->company)->first();

and everything works as expected.

Thanks to everyone!

Upvotes: 1

AntonyMN
AntonyMN

Reputation: 921

First, define the variables

$user_id = $request->session()->get('usrid');
$user = User::find($user_id);

Then, you need to find the user and the companies they are attached, and an individual company with the search params

$companies = $user->company()->get();

$company = $user->company()->where('code', $request->company)->first();

Upvotes: 0

Related Questions