How to query with Eloquent, all users without a certain type of certificate?
Laravel 4
I've got 2 tables:
users table:
->id
->name
certificats table:
->id
->user_id
->certificate_type
I`m struggling with this for hours now. Last thing i tried was:
$users = User::with(array('certificate' => function($query)
{
$query->where('type','!=','SL');
}))->get();
This gives me all the users, but i was trying to get all the users without certificate type 'SL'.
-- edit:
Spencer7593's raw query below works. But i`m not getting the eloquent query to work.
SELECT u.*
FROM users u
LEFT
JOIN certificates c
ON c.user_id = u.id
AND c.type = 'SL'
WHERE c.user_id IS NULL
The relationship:
public function certificate(){
return $this->hasMany('Certificate');
}
public function certificate(){
return $this->belongsTo('User');
}
The SQL to get the result set you want is fairly simple.
SELECT u.*
FROM users u
LEFT
JOIN certificates c
ON c.user_id = u.id
AND c.type = 'SL'
WHERE c.user_id IS NULL
That's a familiar pattern called an "anti-join". Basically, it's a LEFT JOIN look for matching rows, along with rows from users that don't have a match, and then filter out all rows that did get a match, and we're left with rows from users that don't have match.
The trick is going to be getting Eloquent to generate that SQL for you. To get Eloquent to do that, you need to tell eloquent to do a LEFT JOIN, and add a WHERE clause,
maybe something like this would be close:
->left_join('certificate AS c', function($join){
$join->on('c.user_id','=','user.id');
$join->and_on('c.type','=','SL');
})
->where_null('c.user_id')
FOLLOWUP
(For the benefit of those who might not read the comments)
Klass Terst (OP), reports syntax problems in the attempt at Eloquent (in the answer above): left_join needed to be replaced with leftJoin, and the and_on wasn't recognized. (The latter may have been my invention, based on the convention used in with where, and_where, or_where.)
$users = DB::table('users')
->select('users.id','users.name')
->leftJoin('certificate AS c', function($join){
$join->on('c.user_id','=','user.id');
$join->on('c.type','=','SL');
})
->where_null('c.user_id');
I believe the problem is in your relationships.
Models
class User extends Eloquent
{
public function certificates()
{
return $this->hasMany('Certificate');
}
}
class Certificate extends Eloquent
{
public function user()
{
return $this->belongsTo('User');
}
}
Controller
$users = User::with(array('certificates' => function($query)
{
$query->where('type','!=','SL');
}))->get();
return View::make('yourView')->with('users',$users);
View
#foreach($users as $user)
{{ $user->name }} // User's name
#foreach($user->certificates as $certificate)
{{ $certificate->certificate_type }} // Certificate type shouldn't be 'SL'
#endforeach
#endforeach
I hope this helps!
Related
I am trying to exclude a few records from a select that has a null column in its relationship.
This is the query I hope to achieve:
SELECT
FROM modelas ma WHERE
ma.id NOT IN (SELECT ma_id from modelbs where modelbs.updated_at is null)
Model A:
public function modelb(){
return $this->hasMany('App\Modelb');
}
Model B
public function modela(){
return $this->belongsTo('App\Modela');
}
Now, I want to query all models A that have a model B where a certain column of model B ISN'T null.
Here's how i tried:
Modela::whereHas('modelbs', function ($query) {
$query->whereNotNull('myColumnOfModelB');
})->get();
This gave me exactly the records I wanted to exclude from my select
Well, I was able to find out where I was mistaken. So here is a query that achieves that raw sql:
Modela::whereDoesntHave('modelbs', function ($query) {
$query->whereNull('someModelBcolumn');
})->get()
Raw SQL
SELECT
FROM modelas ma WHERE
ma.id NOT IN (SELECT ma_id from modelbs where modelbs.updated_at is null)
The "whereDoesntHave()" is equivalent to "SELECT FROM modelas ma WHERE ma.id NOT IN" whereas the "$query->whereNull()" is the actual subquery equivalent to "(SELECT ma_id from modelbs where modelbs.updated_at IS NULL)"
I have two tables, say "users" and "users_actions", where "users_actions" has an hasMany relation with users:
users
id | name | surname | email...
actions
id | id_action | id_user | log | created_at
Model Users.php
class Users {
public function action()
{
return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc');
}
}
Now, I want to retrieve a list of all users with their LAST action.
I saw that doing Users::with('action')->get();
can easily give me the last action by simply fetching only the first result of the relation:
foreach ($users as $user) {
echo $user->action[0]->description;
}
but I wanted to avoid this of course, and just pick ONLY THE LAST action for EACH user.
I tried using a constraint, like
Users::with(['action' => function ($query) {
$query->orderBy('created_at', 'desc')
->limit(1);
}])
->get();
but that gives me an incorrect result since Laravel executes this query:
SELECT * FROM users_actions WHERE user_id IN (1,2,3,4,5)
ORDER BY created_at
LIMIT 1
which is of course wrong. Is there any possibility to get this without executing a query for each record using Eloquent?
Am I making some obvious mistake I'm not seeing? I'm quite new to using Eloquent and sometimes relationship troubles me.
Edit:
A part from the representational purpose, I also need this feature for searching inside a relation, say for example I want to search users where LAST ACTION = 'something'
I tried using
$actions->whereHas('action', function($query) {
$query->where('id_action', 1);
});
but this gives me ALL the users which had had an action = 1, and since it's a log everyone passed that step.
Edit 2:
Thanks to #berkayk looks like I solved the first part of my problem, but still I can't search within the relation.
Actions::whereHas('latestAction', function($query) {
$query->where('id_action', 1);
});
still doesn't perform the right query, it generates something like:
select * from `users` where
(select count(*)
from `users_action`
where `users_action`.`user_id` = `users`.`id`
and `id_action` in ('1')
) >= 1
order by `created_at` desc
I need to get the record where the latest action is 1
I think the solution you are asking for is explained here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/
Define this relation in User model,
public function latestAction()
{
return $this->hasOne('Action')->latest();
}
And get the results with
User::with('latestAction')->get();
I created a package for this: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit trait in both the parent and the related model.
class User extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Action extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then simply chain ->limit(1) call in your eager-load query (which seems you already do), and you will get the latest action per user.
My solution linked by #berbayk is cool if you want to easily get latest hasMany related model.
However, it couldn't solve the other part of what you're asking for, since querying this relation with where clause would result in pretty much the same what you already experienced - all rows would be returned, only latest wouldn't be latest in fact (but latest matching the where constraint).
So here you go:
the easy way - get all and filter collection:
User::has('actions')->with('latestAction')->get()->filter(function ($user) {
return $user->latestAction->id_action == 1;
});
or the hard way - do it in sql (assuming MySQL):
User::whereHas('actions', function ($q) {
// where id = (..subquery..)
$q->where('id', function ($q) {
$q->from('actions as sub')
->selectRaw('max(id)')
->whereRaw('actions.user_id = sub.user_id');
})->where('id_action', 1);
})->with('latestAction')->get();
Choose one of these solutions by comparing performance - the first will return all rows and filter possibly big collection.
The latter will run subquery (whereHas) with nested subquery (where('id', function () {..}), so both ways might be potentially slow on big table.
Let change a bit the #berkayk's code.
Define this relation in Users model,
public function latestAction()
{
return $this->hasOne('Action')->latest();
}
And
Users::with(['latestAction' => function ($query) {
$query->where('id_action', 1);
}])->get();
To load latest related data for each user you could get it using self join approach on actions table something like
select u.*, a.*
from users u
join actions a on u.id = a.user_id
left join actions a1 on a.user_id = a1.user_id
and a.created_at < a1.created_at
where a1.user_id is null
a.id_action = 1 // id_action filter on related latest record
To do it via query builder way you can write it as
DB::table('users as u')
->select('u.*', 'a.*')
->join('actions as a', 'u.id', '=', 'a.user_id')
->leftJoin('actions as a1', function ($join) {
$join->on('a.user_id', '=', 'a1.user_id')
->whereRaw(DB::raw('a.created_at < a1.created_at'));
})
->whereNull('a1.user_id')
->where('aid_action', 1) // id_action filter on related latest record
->get();
To eager to the latest relation for a user you can define it as a hasOne relation on your model like
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class User extends Model
{
public function latest_action()
{
return $this->hasOne(\App\Models\Action::class, 'user_id')
->leftJoin('actions as a1', function ($join) {
$join->on('actions.user_id', '=', 'a1.user_id')
->whereRaw(DB::raw('actions.created_at < a1.created_at'));
})->whereNull('a1.user_id')
->select('actions.*');
}
}
There is no need for dependent sub query just apply regular filter inside whereHas
User::with('latest_action')
->whereHas('latest_action', function ($query) {
$query->where('id_action', 1);
})
->get();
Migrating Raw SQL to Eloquent
Laravel Eloquent select all rows with max created_at
Laravel - Get the last entry of each UID type
Laravel Eloquent group by most recent record
Laravel Uses take() function not Limit
Try the below Code i hope it's working fine for u
Users::with(['action' => function ($query) {
$query->orderBy('created_at', 'desc')->take(1);
}])->get();
or simply add a take method to your relationship like below
return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc')->take(1);
I'm working with L5 and elequent
My table structure is..
users
id
other field
auctions
id
other field
lots
id
auction_id
other field
lot_user
lot_id
user_id
I want to find auctions for a user.
How can i do this?
$user = User::find($id);
$auctions = $user->auctions();
I have got an idea to do this with eloquent..
$auctions = $user->lots()
->join('auctions','auctions.id','=','lots.id')
->select(['auctions.*'])
->get();
I'm not sure Eloquent is going to be very efficient here, but you could do something like :
In your User(s) class, you need to define a many-many relationship like :
public function lots()
{
return $this->belongsToMany('App\Lot');
}
In your Lot(s) class, you need to define the inverse of a one-to-many relationship like:
public function auctions()
{
return $this->belongsTo('App\Auction')
}
Then, to get Lots for a user, you'd do something like :
$user->lots();
To get auctions, you'd need to loop over lots and call $lot->auctions() for each one, and then filter by id to get the unique auctions.
This is a case where it would probably be easier to use the DB facade to built a query instead of just trying to use Eloquent.
About DB facade.
Raw query will looks like this:
SELECT * FROM auctions AS a
INNER JOIN lots AS l ON (l.auction_id = a.id)
INNER JOIN lot_user AS lu ON (lu.lot_id = l.id AND lu.user_id = $findUserId)
GROUP BY a.id
And using query-builder you can do it like this:
DB::table('auctions')
->join('lots', 'lots.auction_id', '=', 'auctions.id')
->join('lot_user', function ($join) {
$join->on('lot_user.lot_id', '=', 'lots.id')
->where('lot_user.user_id', '=', $findUserId);
})
->groupBy('auctions.id')
->get();
I am trying to link 4 tables and also add a custom field calculated by counting the ids of some related tables using laravel.
I have this in SQL which does what I want, but I think it can be made more efficient:
DB::select('SELECT
posts.*,
users.id AS users_id, users.email,users.username,
GROUP_CONCAT(tags.tag ORDER BY posts_tags.id) AS tags,
COUNT(DISTINCT comments.id) AS NumComments,
COUNT(DISTINCT vote.id) AS NumVotes
FROM
posts
LEFT JOIN comments ON comments.posts_id = posts.id
LEFT JOIN users ON users.id = posts.author_id
LEFT JOIN vote ON vote.posts_id = posts.id
LEFT JOIN posts_tags ON posts_tags.posts_id = posts.id
LEFT JOIN tags ON tags.id = posts_tags.tags_id
GROUP BY
posts.id,
posts.post_title');
I tried to implement it using eloquent by doing this:
$trending=Posts::with(array('comments' => function($query)
{
$query->select(DB::raw('COUNT(DISTINCT comments.id) AS NumComments'));
},'user','vote','tags'))->get();
However the NumComments value is not showing up in the query results.
Any clue how else to go about it?
You can't do that using with, because it executes separate query.
What you need is simple join. Just translate the query you have to something like:
Posts::join('comments as c', 'posts.id', '=', 'c.id')
->selectRaw('posts.*, count(distinct c.id) as numComments')
->groupBy('posts.id', 'posts.post_title')
->with('user', 'vote', 'tags')
->get();
then each post in the collection will have count attribute:
$post->numComments;
However you can make it easier with relations like below:
Though first solution is better in terms of performance (might not be noticeable unless you have big data)
// helper relation
public function commentsCount()
{
return $this->hasOne('Comment')->selectRaw('posts_id, count(*) as aggregate')->groupBy('posts_id');
}
// accessor for convenience
public function getCommentsCountAttribute()
{
// if relation not loaded already, let's load it now
if ( ! array_key_exists('commentsCount', $this->relations)) $this->load('commentsCount');
return $this->getRelation('commentsCount')->aggregate;
}
This will allow you to do this:
$posts = Posts::with('commentsCount', 'tags', ....)->get();
// then each post:
$post->commentsCount;
And for many to many relations:
public function tagsCount()
{
return $this->belongsToMany('Tag')->selectRaw('count(tags.id) as aggregate')->groupBy('pivot_posts_id');
}
public function getTagsCountAttribute()
{
if ( ! array_key_exists('tagsCount', $this->relations)) $this->load('tagsCount');
$related = $this->getRelation('tagsCount')->first();
return ($related) ? $related->aggregate : 0;
}
More examples like this can be found here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/
as of laravel 5.3 you can do this
withCount('comments','tags');
and call it like this
$post->comments_count;
laravel 5.3 added withCount
I have been trying to convert a right join query to left join query in order to use it inside laravel query builder. Here is my Sql statement and it result wich works flawlessly
select `weekday`.`name`, `open_time`, `close_time`
from `schedule`
join `restaurants_has_schedule` on `schedule`.`id` = `restaurants_has_schedule`.`schedule_id`
and `restaurants_has_schedule`.`restaurants_id` = 1
right join `weekday` on `weekday`.`id` = `schedule`.`weekday_id`
ORDER BY `weekday`.`id`
|------
|name|open_time|close_time
|------
|Domingo|NULL|NULL
|Lunes|NULL|NULL
|Martes|NULL|NULL
|Miercoles|NULL|NULL
|Jueves|14:11:51|14:11:51
|Vienes|09:11:21|17:00:00
|Sábado|NULL|NULL
but when convert It to left join it stop working, displaying me the same data for every single restaurants_id. This is my left join statement.
select `weekday`.`name`, `open_time`, `close_time`
from `weekday`
left join `schedule` on `weekday`.`id` = `schedule`.`weekday_id`
join `restaurants_has_schedule` on `schedule`.`id` = `restaurants_has_schedule`.`schedule_id`
and `restaurants_has_schedule`.`restaurants_id` = 1
ORDER BY `weekday`.`id`
What am I doing wrong? Is There another alternative? Thak you in advance
Try use Laravels Eloquent ORM, which handles relationships really cool! no need anymore to concat or write sql-queries
See here about: Laravels Eloquent ORM & Schema Builder
Or maybe about orm's in general, you should really give it a try:
Object Role Modeling
Object Role Modeling
Example from Laravel doc:
One Post may have many comments
One to many:
class Post extends Eloquent {
public function comments()
{
return $this->hasMany('Comment');
}
}
Where 'Comment' is the model.
The "reverse" to define:
class Comment extends Eloquent {
public function post()
{
return $this->belongsTo('Post');
}
}
Where 'Post' is the model.
And then as query:
$comments = Post::find(1)->comments; //by Primary Key
Or
$comments = Post::where('somefield', '=', 'somevalue')->comments->get();
....Really cool, for many to many see the docs#Laravels Eloquent ORM