Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using laravel eloquent relation to retrieve all records except NULL

Tags:

php

laravel

Is there a way to retrieve all the records which has not null using eloquent model.

e.g.

I have relation setup

Plate model

public function project()
{
    return $this->hasOne('App\Models\Project');
}

project model

public function plate()
{
    return $this->belongsTo('App\Models\Plate');
}

How can I retrieve all the records which have value.

trying this return $p = \App\Models\Plate::with('project')->get();

will return everything, even those who have NULL.

enter image description here

All I want is plates which have projects attached to. I tried laravel documentation, but could't find anything. Is there also same approach for many relations

like image 220
user3641381 Avatar asked Nov 17 '15 14:11

user3641381


People also ask

How do you check if not null with eloquent?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

What is hasMany relationship in Laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .


1 Answers

You can use the has method to only retrieve plates that have a project.

\App\Models\Plate::with('project')->has('project')->get();

Docs on has: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

like image 114
Thomas Kim Avatar answered Oct 18 '22 22:10

Thomas Kim