Select all where latest relation is true? - php

I have a system in which many items can be approved and the history of approvals can be seen on each item. An example is a user's milestone, which can be approved or rejected. The tables in my database book like this:
+-----------------+------------------+
| Approvals |
+-----------------+------------------+
| Field | Type |
+-----------------+------------------+
| id | int(10) unsigned |
| approved | tinyint(1) |
| reason | text |
| approvable_id | varchar(191) |
| approvable_type | varchar(191) |
| created_at | timestamp |
| updated_at | timestamp |
+-----------------+------------------+
+----------------------+---------------------------------------+
| Milestones |
+----------------------+---------------------------------------+
| Field | Type |
+----------------------+---------------------------------------+
| id | int(10) unsigned |
| name | varchar(191) |
| created_at | timestamp |
| updated_at | timestamp |
+----------------------+---------------------------------------+
What I want to be able to do is fetch all milestones where the last approval is accepted. For example a milestone may have been previously accepted, but later reject, in which case this milestone should not appear in the accepted query, as it has since been rejected.
How can I only fetch milestones in which the latest approval is accepted? The approach I have tried so far is to make an exist sub query which checks if milestones has an approval, that is accepted. However, this also fetches results which have been accepted and later rejected:
SELECT * FROM `milestones`
WHERE EXISTS (
SELECT * FROM `approvals`
WHERE `milestones`.`id` = `approvals`.`approvable_id`
AND `approvals`.`approvable_type` = 'App\Models\Milestone'
AND `created_at` = (
SELECT MAX(created_at) FROM `approvals` AS `sub`
WHERE sub.approvable_id = approvals.approvable_id
AND sub.`approvable_type` = `approvals`.`approvable_type`
AND `sub`.`id` IN (
SELECT `id` FROM `approvals`
WHERE `approved` = 1
)
)
) AND `milestones`.`deleted_at` IS NULL
Is it possible to grab all milestones where the latest approval is accepted? Or would this have to be done on the application level instead?

This should do the job
select m.*,a.*
from milestones m
join approvals a on m.id = a.approvable_id
join (
select approvable_id, max(created_at) created_at
from approvals
group by approvable_id
) aa on a.approvable_id = aa.approvable_id
and a.created_at = aa.created_at
where a.approved = 1 /* other filters in query */
First it will join each milestone with the latest record from approvals table and then in where clause it filter out the latest approvals with approved = 1

Since you tagged this with Laravel and you've set up the morphable relationships, even though you're writing plain SQL, I'm going to show you the Laravel (Eloquent) way.
If I'm understanding you correctly, using Laravel's Polymorphic Relationships I think this should work:
Approval.php
<?php
namespace App\Models;
use App\Models\Milestone;
use Illuminate\Database\Eloquent\Model;
class Approval extends Model
{
public function approvable()
{
return $this->morphTo();
}
}
Milestone.php
<?php
namespace App\Models;
use App\Models\Approval;
use Illuminate\Database\Eloquent\Model;
class Milestone extends Model
{
/**
* All approvals
*
* #return MorphMany
*/
public function approvals()
{
return $this->morphMany(Approval::class, 'approvable');
}
/**
* The most recent "approved" approval
*
* #return MorphMany
*/
public function lastestApproval()
{
return $this->morphMany(Approval::class, 'approvable')->where('approved', 1)->latest()->limit(1);
}
}
Then to get all Milestones with their most recent approval:
$milestones = App\Models\Milestone::with('lastestApproval')->get();
Here's what the DB structure looks like (should be the same as yours):

As tptcat pointed out, this question is tagged as a Laravel question. So using M Khalid Junaid's answer I converted it into Eloquent syntax (Or as much as I could) and got the following:
public function scopeApproved($query, $accepted=true)
{
return $query->select('milestones.*', 'approvals.*')
->join('approvals', 'milestones.id', '=', 'approvals.approvable_id')
->join(\DB::raw(
'(SELECT approvable_id, MAX(created_at) created_at
FROM approvals
GROUP BY approvable_id) aa' ), function($join)
{
$join->on('approvals.approvable_id', '=', 'aa.approvable_id')
->on('approvals.created_at', '=', 'aa.created_at');
})->where('approvals.approved', $accepted);
}

Related

Get results by finding an ID which is two joins away using Eloquent relationships

I need to get rows from one table using an id which is two joins away.
I know I can use join('table_name') but I am trying to use the model names rather than raw table names.
I'm trying to select shipping_shipment.* by joining order_item_join_shipping_shipment then joining order_item, and filtering where order_item.order_id = x
I tried this in the ShippingShipment class, but I can't figure it out.
return $this->hasManyThrough(OrderItem::class, ShippingShipment::class, 'shipment_id', 'order_item_id', 'id', 'id');
There are many items in an order, and many shipments. I need to get the shipments.
There can be more than one shipment per order - items come from various places.
There can be more than one shipment per item - if something is returned and needs shipping again.
The table I want to get rows from, shipping_shipment, is joined to order_item by a join table order_item_join_shipping_shipment. That join table has the order_item_id. I need then to join order_item table so that I can search for order_item.order_id
Table order_item model OrderItem
+-----+---------------+
| id | order_id |
+-----+---------------+
| 6 | 13464 |
| 8 | 13464 |
| 9 | 13464 |
+-----+---------------+
Table order_item_join_shipping_shipment model OrderItemJoinShippingShipment
+-----+---------------+-------------+
| id | order_item_id | shipment_id |
+-----+---------------+-------------+
| 1 | 6 | 12 |
| 1 | 9 | 12 | two items in one shipment
| | | |
| 2 | 8 | 13 |
| 3 | 8 | 14 | one item was returned so shipped again
+-----+---------------+-------------+
Table shipping_shipment don't need describing except to say it has an id column.
If I was to do it with MySQL it would look like this
SELECT ss.*, oiss.order_item_id FROM
order_item_join_shipping_shipment AS oiss
INNER JOIN shipping_shipment AS ss ON (oiss.shipment_id = ss.id)
INNER JOIN order_item AS oi ON (oiss.order_item_id = oi.id)
WHERE oi.order_id = 13464
I noticed you are not using the default table names, so your Models must have the table names explicit, e.g.:
class OrderItem extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'order_item';
}
In the same Model file of the above example, you need to indicate how the relationship works, i.e.:
public function shippingShipments()
{
return $this->belongsToMany(ShippingShipment::class, 'order_item_join_shipping_shipment', 'order_item_id', 'shipment_id');
}
Here you can check in Laravel documentation the whole explanation.
You need to apply the same concept in ShippingShipment Model, so your Model will be something like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'order_item';
/**
* The roles that belong to the user.
*/
public function orderItens()
{
return $this->belongsToMany(OrderItem::class, 'order_item_join_shipping_shipment', 'shipment_id', 'order_item_id');
}
}
This way you can get shipments by order item and vice-versa:
//Shipments of Order item 13464
$shipments = OrderItem::find(13464)->shippingShipments()->get();
//Order items of Shipment 1
$orders = ShippingShipment::find(1)->orderItems()->get();
Source: Laravel Documentation
As far as I can tell you are using a pivot table between ShippingShipment and OrderItem. If I understand you correctly you want to get OrderItems that are connected to ShippingShipment, if that is the case this is what you can do:
Make belongs to many relationships in both models, such as:
ShippingShipment:
public function orderItems(){
return $this->belongsToMany(OrderItem::class, 'table_name', 'column_id');
}
OrderItem:
public function shippingShipment(){
return $this->belongsToMany(ShippingShipment::class, 'table_name', 'column_id');
}
And then you can get the desired result by typing this query:
ShippingShipment::find(1)->with('orderItems')->get();
OrderItem::find(13464)->with('shippingShipments')->get();
Note: you can use orderItems:id,order or shippingShipment:id,some_other_field for more optimized query

Doctrine getting relational entites by status flag

I have 3 tables users, groups, group_users (holds relation between group and user)
The table of group_users includes the following columns
-- (is_active 0: not active, 1: active)
| id | user_id | group_id | is_active |
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 0 |
In entity of Group I have a relational column like the following that gets group users using the relation in group_users table
/*
* #ORM\Entity()
* #ORM\Table(name="groups")
*/
class Group{
...
/**
* #var Collection|GroupUser[]
* #ORM\OneToMany(targetEntity="App\Group\Domain\Entity\GroupUser")
*/
private $group_users;
In entity of Group I want to get group users but only ones that are active. In normal condition the relation above gets all related entities.
If I need to give an example, according to above records in group_users table, when I call variable like $this->group_users I want to see that only first record is listed
| id | user_id | group_id | is_active |
| 1 | 1 | 1 | 1 |
not this
| id | user_id | group_id | is_active |
| 2 | 1 | 2 | 0 |
Do you have any idea what's the best way to handle this problem, thanks.
Note: I don't want to physically delete any record.
You can define a new getter in Group entity which will filter out the related group users as per your criteria
use Doctrine\Common\Collections\Criteria;
class Group{
//...
protected getActiveGroupUsers() {
$criteria = \Doctrine\Common\Collections\Criteria::create()
->where(\Doctrine\Common\Collections\Criteria::expr()->eq("is_active", 1));
return $this->group_users->matching($criteria);
}
}
And when you query a group you can get the related active group users as
$group = $em->getRepository("...\Group")->find($id);
$group->getActiveGroupUsers();
How filter data inside entity object in Symfony 2 and Doctrine

A little complex query using eloquent

I am trying to learn laravel and currently using eloquent to interact with the database. I am stuck on how I could use eloquent to get a kind of a join in eloquent.
I have a many to many relation between two tables :users and projects , I use sharedProject table to be the intermediate table .
The tables are as such
Users:
| iduser | name | password |
----------------------------------------
| 1 | somename | hashPassword |
| 2 | somename2 | hashPassword |
| 3 | somename3 | hashPassword |
| 4 | somename4 | hashPassword |
----------------------------------------
Projects:
| pid | projectname
-------------------
| 1 | somename
| 2 | somename
SharedProjects:
| pid | iduser | sharedProjectid |
----------------------------------
| 1 | 1 | 1 |
| 1 | 2 | 2 |
Now I want to get all the users who are not sharing a given project, for example in the above case for project with id 1 , I should get user 3 and user 4.
Here are my relationships in User model
/**
* User can have many projects
*
* #var array
*/
public function projects(){
return $this->hasMany('App\Project','pid','iduser'); // hasmany(model,foreignkey,localkey)
}
/**
* The user can have many shared projects
*/
public function sharedProjects()
{
return $this->belongsToMany('App\SharedProject', 'sharedProjects', 'iduser', 'pid');// belongsToMany('intermediate tablename','id1','id2')
}
and in the Project model:
/**
* The project can be shared by many users
*/
public function sharedProjects()
{
return $this->belongsToMany('App\SharedProject', 'sharedProjects', 'pid', 'iduser');// belongsToMany('intermediate tablename','id1','id2')
}
/**
* a project belongs to a single user
*
* #var array
*/
public function user()
{
return $this->belongsTo('App\User');
}
I would prefer a eloquent way to do this , but would also except it, if can't be done in eloquent and I have to see a alternate approach I would appreciate a plain mysql query as well.
Thanks
Once you define your Eloquent models and your many-to-many relationships, you can use them to get the data you're looking for.
Assuming a User model that has a projects relationship defined, you can use the whereDoesntHave() method to query for a list of users that are not related to a specific project.
$projectId = 1;
$users = User::whereDoesntHave('projects', function ($q) use ($projectId) {
return $q->where('projects.id', $id);
})->get();
You can read about defining many-to-many relationships in Eloquent here.
You can read about querying relationship existence here.
As you may notice, not all methods are documented (like whereDoesntHave()), so you may have to go source code diving. You can dig into the Eloquent codebase here.
I resort to use plain mysql queries, this seems to work for me:
$nonSharedUsers = DB::select( DB::raw("SELECT iduser FROM users WHERE NOT EXISTS (SELECT * FROM sharedProjects WHERE sharedProjects.iduser= users.iduser and sharedProjects.pid=:projectId)"), array(
'projectId' => $pid,
));

Obtain three level relationship on Laravel 5

I'm trying to obtain a three level relationship data, but I'm lost about it using laravel 5.1
I'll try to explain my scenario, hope you can help me.
I've got two models called Host and User.
This models are grouped by Hostgroup and Usergroup models, using a Many To Many relationship.
Then I've got a table called usergroup_hostgroup_permissions which relation an Usergroup with a Hostgroup:
+--------------+----------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+----------------------+------+-----+---------------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| usergroup_id | int(10) unsigned | NO | MUL | NULL | |
| hostgroup_id | int(10) unsigned | NO | MUL | NULL | |
| action | enum('allow','deny') | NO | | allow | |
| enabled | tinyint(1) | NO | | 1 | |
+--------------+----------------------+------+-----+---------------------+----------------+
I'd like to obtain a list of users that belongs to an usergroup with a relation in this table with a hostgroup where my host belongs to.
For example:
My host_1 belongs to DEV_servers.
On usergroup_hostgroup_permissions table, there's an entry that allows developers to access to DEV_servers.
The usergroup developer has 3 users user_1, user_2 and user_3.
Any hint? Thanks in advance!
In order to obtain a list of users in a particular host, you need to nest all the underlying relationships (via .) using a whereHas method on the User model. i.e.
$users = User::whereHas('usergroup.hostgroups.hosts', function($q) use ($hostID){
$q->where('id', $hostID);
})->get();
Moreover, if you want to check against whether the user is allowed to access that particular host, then you may chain another where() to the above as such:
$users = User::whereHas('usergroup.hostgroups.hosts', function($q) use ($hostID){
$q->where('id', $hostID)->where('usergroup_hostgroup_permissions.action', 'allow');
})->get();
Note: If you are warned on an ambiguous id field, try including the table hosts to which the id belongs to as well, i.e. hosts.id.
I am assuming that you have defined the relations for those models as follows:
class HostGroup extends Eloquent {
/** ...
*/
public function hosts(){
return $this->hasMany('App\Host');
}
public function usergroups(){
return $this->belongsToMany('App\UserGroup', 'usergroup_hostgroup_permissions');
}
}
class Host extends Eloquent {
/** ...
*/
public function hostgroup() {
return $this->belongsTo('App\HostGroup');
}
}
class UserGroup extends Eloquent {
/** ...
*/
public function users(){
return $this->hasMany('App\User');
}
public function hostgroups(){
return $this->belongsToMany('App\HostGroup', 'usergroup_hostgroup_permissions');
}
}
class User extends Eloquent {
/** ...
*/
public function usergroup(){
return $this->belongsTo('App\UserGroup');
}
}
Hope it turns out to be helpful.

Merge and Sort two Eloquent Collections?

I've two Collections and I want merge it to one variable (of course, with ordering by one collumn - created_at). How Can I do that?
My Controllers looks that:
$replies = Ticket::with('replies', 'replies.user')->find($id);
$logs = DB::table('logs_ticket')
->join('users', 'users.id', '=', 'mod_id')
->where('ticket_id', '=', $id)
->select('users.username', 'logs_ticket.created_at', 'action')
->get();
My Output looks for example:
Replies:
ID | ticket_id | username | message | created_at
1 | 1 | somebody | asdfghj | 2014-04-12 12:12:12
2 | 1 | somebody | qwertyi | 2014-04-14 12:11:10
Logs:
ID | ticket_id | username | action | created_at
1 | 1 | somebody | close | 2014-04-13 12:12:14
2 | 1 | somebody | open | 2014-04-14 14:15:10
And I want something like this:
ticket_id | table | username | message | created_at
1 |replies| somebody | asdfghj | 2014-04-12 12:12:12
1 | logs | somebody | close | 2014-04-13 12:12:14
1 | logs | somebody | open | 2014-04-14 11:15:10
1 |replies| somebody | qwertyi | 2014-04-14 12:11:10
EDIT:
My Ticket Model looks that:
<?php
class Ticket extends Eloquent {
protected $table = 'tickets';
public function replies() {
return $this->hasMany('TicketReply')->orderBy('ticketreplies.created_at', 'desc');
}
public function user()
{
return $this->belongsTo('User');
}
}
?>
A little workaround for your problem.
$posts = collect(Post::onlyTrashed()->get());
$comments = collect(Comment::onlyTrashed()->get());
$trash = $posts->merge($comments)->sortByDesc('deleted_at');
This way you can just merge them, even when there are duplicate ID's.
You're not going to be able to get exactly what you want easily.
In general, merging should be easy with a $collection->merge($otherCollection);, and sort with $collection->sort();. However, the merge won't work the way you want it to due to not having unique IDs, and the 'table' column that you want, you'll have to make happen manually.
Also they are actually both going to be collections of different types I think (the one being based on an Eloquent\Model will be Eloquent\Collection, and the other being a standard Collection), which may cause its own issues. As such, I'd suggest using DB::table() for both, and augmenting your results with columns you can control.
As for the code to achieve that, I'm not sure as I don't do a lot of low-level DB work in Laravel, so don't know the best way to create the queries. Either way, just because it's looking like starting to be a pain to manage this with two queries and some PHP merging, I'd suggest doing it all in one DB query. It'll actually look neater and arguably be more maintainable:
The SQL you'll need is something like this:
SELECT * FROM
(
SELECT
`r`.`ticket_id`,
'replies' AS `table`,
`u`.`username`,
`r`.`message`,
`r`.`created_at`
FROM `replies` AS `r`
LEFT JOIN `users` AS `u`
ON `r`.`user_id` = `u`.`id`
WHERE `r`.`ticket_id` = ?
) UNION (
SELECT
`l`.`ticket_id`,
'logs' AS `table`,
`u`.`username`,
`l`.`action` AS `message`,
`l`.`created_at`
FROM `logs` AS `l`
LEFT JOIN `users` AS `u`
ON `l`.`user_id` = `u`.`id`
WHERE `l`.ticket_id` = ?
)
ORDER BY `created_at` DESC
It's pretty self-explanatory: do the two queries, returning the same columns, UNION them and then sort that result set in MySQL. Hopefully it (or something similar, as I've had to guess your database structure) will work for you.
As for translating that into a Laravel DB::-style query, I guess that's up to you.

Categories