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)"
Related
I have the following relationships in models:
Product.php
public function skus()
{
return $this->belongsToMany(Sku::class);
}
Sku.php
public function prices()
{
return $this->hasMany(Price::class);
}
I need to get an attribute indicating whether a product has at least one price or not (in the extreme case, just the number of prices).
Product::withExists('sku.prices') or Product::withCount('sku.prices')
I know about this repository https://github.com/staudenmeir/belongs-to-through, but I prefer to use complex query once
UPDATE: I have already written a sql query for this purpose, but I don't know how to do it in Laravel:
SELECT
*,
EXISTS (SELECT
*
FROM prices
INNER JOIN skus
ON prices.sku_id = skus.id
INNER JOIN product_sku
ON skus.id = product_sku.sku_id
WHERE products.id = product_sku.product_id
) AS prices_exists
FROM products
Here you can get at least one record
$skuPrice = Sku::with('prices')
->has('prices', '>=', 1)
->withCount('prices')
->get();
I have show (only show, not compleate CRUD) the result of a query which is built as following:
SELECT SUM(a) AS ab, b, COUNT(*) as C
FROM x
INNER JOIN y
ON y.a = x.a
WHERE b=123
GROUP BY b
so I built this query with ActiveRecord in SearchModels search() method.
In the model of table a I added a hasOne()-relation.
To display the data of this query, I'm using GridView. In it's columns array I use y.b and so on...
My problem: The columns from table x are displayed correct, but for every "joined column" from table y it displays (not set).If I print the by ActiveRecord builded query, and execute it in my sql client, it displays all data. I guess this is depending on the Models primaryKey() function, but I can't change it to get the table work properly. Does somebody know a solution for my problem or why dataProvider/GridView takes care of the selected model's (in this case model of table x) primaryKey() method (or how to make dataProvider/GridView ignore the primaryKey()?
In model you should create relation method with relation model.
For example:
class Patient extends ActiveRecord
{
public function getOrders()
{
return $this->hasMany(Order::class, ['patient_id' => 'id']);
}
}
class Order extends ActiveRecord
{
public function getPatient()
{
return $this->hasOne(Patient::class, ['id' => 'patient_id']);
}
}
For access data:
// SELECT * FROM `patient` WHERE `id` = 1
$patient = Patient::findOne(1);
$orders = $patient->orders;
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 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
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!