Reputation: 63
I'm trying to get the results using laravel many to many relationship but the query is generating wrong therefore it return empty array.
$user->survey()->get()
is returning empty array.
$user->survey()->toSql()
is returning wrong query:
SELECT
*
FROM
`survey`
INNER JOIN `survey_user` ON `survey`.`id` = `survey_user`.`survey_id`
WHERE
`survey_user`.`user_id` IS NULL
Here, in the end, the user_id should not be null.
Migration for the survey pivot table:
Schema::create('survey_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('survey_id')->unsigned();
$table->string('status', 50)->nullable();
$table->timestamps();
});
Schema::table('survey_user', function (Blueprint $table) {
$table->foreign('user_id')->on('users')->references('id');
$table->foreign('survey_id')->references('id')->on('survey')
->onDelete('cascade')
->onUpdate('cascade');
});
}
here are the two relation:
public function survey()
{
return $this->belongsToMany(Survey::class, 'survey_user')
->withPivot('status')
->withTimestamps();
}
public function user()
{
return $this->belongsToMany(User::class, 'survey_user')
->withPivot('status')
->withTimestamps();
}
I'm just trying to get all the users who have survey assigned in their pivot.
$user = new User();
var_dump($user->survey()->get());
Upvotes: 0
Views: 647
Reputation: 5552
I'm just trying to get all the users who have survey assigned in their pivot.
To get all Users where the survey
relationship exists, your code would look like this:
$users = User::has('survey')->get();
If you need the survey
relationship loaded on the models when you use them, then add with()
to eager load the relationship:
$users = User::has('survey')
->with('survey')
->get();
Here, in the end, the user_id should not be null.
The reason it was searching with a null user id is because you are searching with a new User
instance that hasn't been saved to the database. This is your code with the problem:
$user = new User();
var_dump($user->survey()->get());
Since $user
is a new object that hasn't been saved to the database it doesn't have an id. When you call $user->survey()
it builds a query to search survey_user
where the user id is null.
Upvotes: 0