Friday, April 14, 2017

Why hasOne and HasMany generate the same Sql query in Eloquent?

I have two Models:

class User extends Eloquent
{
    public function phone()
    {
        return $this->hasOne('App\Models\Phone');
    }

    public function phones()
    {
        return $this->hasMany('App\Models\Phone');
    }
}

class Phone extends Eloquent
{
    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }
}

If User::first()->phone()->toSql() and User::first()->phone()->toSql() generate the same raw query:

select * from `phones` where `phones`.`user` = ? and `phones`.`user` is not null

What is the difference between hasOne and hasMany relationships?



via tarrsalah

Advertisement