Because there's an option to make a foreign key constraint nullable in the migration. I mean, the column.
Aug 27, 2016
6
Level 4
why laravel add an extra where condition "foreign key is not null" to hasOne/Many relation?
I don't think this is a big deal and I just wonder why.
let's just say, a product variant could hasOne(Price::class)
$variant->price will generate sql like this:
SELECT *
FROM `prices`
WHERE `prices`.`variant_id` = 17 and `prices`.`variant_id` is not null
LIMIT 1
here is the code from Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
/**
* Set the base constraints on the relation query.
*
* @return void
*/
public function addConstraints()
{
if (static::$constraints) {
$this->query->where($this->foreignKey, '=', $this->getParentKey());
$this->query->whereNotNull($this->foreignKey);
}
}
I don't quite understand why laravel will add this extra "whereNotNull on foreign key" .
I find it redundant but I'm not 100% sure.
Please or to participate in this conversation.