I can think of several ad-hoc ways to do this, but I'm really looking for a 'best practices' type of solution.
I have 3 tables involved
- users (user_id)
- usages ('user_id', 'provider_id', 'nurse_id', 'patient_id')
- usage_alerts ('usage_id')
Im trying to eager load alerts using hasManyThrough() based on a user's role.
The user_id field is agnostic, and can apply to any role, so merging and filtering needs to take place.
Using $this->hasManyThrough('UsageAlert', 'Usage')->get() will return a collection, making the ->merge() method available. However, when eager loading, on return, i get an error since it's a collection object.
Call to undefined method Illuminate\Database\Eloquent\Collection::addEagerConstraints()
For example, this is my current relation (returns the error above)
public function alerts()
{
$alerts = $this->hasManyThrough('UsageAlert', 'Usage')->get();
if(Sentry::getUser()->inGroup(Sentry::findGroupByName('provider')))
$alerts->merge($this->hasManyThrough('UsageAlert', 'Usage', 'provider_id'));
if(Sentry::getUser()->inGroup(Sentry::findGroupByName('patient')))
$alerts->merge($this->hasManyThrough('UsageAlert', 'Usage', 'patient_id'));
if(Sentry::getUser()->inGroup(Sentry::findGroupByName('nurse')))
$alerts->merge($this->hasManyThrough('UsageAlert', 'Usage', 'nurse_id'));
return $alerts;
}
Any suggestions? Pperhaps too much complexity for a relationship?
Best practice manipulates the relationship, though official documentation on how lacks. For your scenario, you can union the additional queries into the primary "agnostic" relationship:
$relation = $this->hasManyThrough('UsageAlert', 'Usage');
foreach (['provider','patient','nurse'] as $group) {
if (Sentry::getUser()->inGroup(Sentry::findGroupByName($group))) {
$relation->getBaseQuery()->union(
$this->
hasManyThrough('UsageAlert', 'Usage', $group . '_id')->
getBaseQuery()->
select('UsageAlert.*') // limits union to common needed columns
);
}
}
return $relation;
This approach returns a Relation, rather than a Collection, as would be expected by API users.
Related
i'm really new working with laravel 5.0, so I got this problem when I try to retrieve a result using a model. I have a users table, with a list of users who can be a manager or not, they can have assigned one or more companies, or none, a company table with companies which can have one or many managers, and a pivot table that I called companies_managers. I set up the relations in every model like this:
/***User model***/
public function companies()
{
return $this->belongsToMany('App\Company', 'companies_managers','id', 'manager_id');
}
and the same in Company model
public function managers()
{
return $this->belongsToMany('App\User', 'companies_managers', 'id', 'company_id');
}
I want to get the managers assigned to a company using a company id to get it, but it just gave me an huge object without the values I looking for (the names of the managers assigned to that company). This is the code that I tried:
$managers = Company::find($id)->managers();
I would appreciate any help you can give me
Using ->managers() (with the brackets) doesn't actually return the associated managers, but rather a Builder instance (the "huge object"), which you can then chain with additional parameters before finally retrieving them with ->get() (or another closure, like ->first(), ->paginate(), etc)
Using ->managers (without the brackets), will attempt to access the associated managers, and execute any additional logic to retrieve them.
So, you have 2 options:
$company = Company::with(["managers"])->findOrFail($id);
$managers = $company->managers;
Or
$company = Company::findOrFail($id);
$managers = $company->managers()->get();
Both of those will perform the necessary logic to pull the managers. ->with() and no brackets is slightly more efficient, doing it all in a single query, so bear that in mind.
You just need to split out your code;
// this will find the company based on the id, or if it cannot find
// it will fail so will abort the application
$company = Company::findOrFail($id);
// this uses the active company record and gets the managers based
// on the current company
$managers = $company->managers;
Thank you for your help guys, I solved the issue fixing the relations in the models to this:
return $this->belongsToMany('App\Company', 'companies_managers', 'manager_id', 'company_id');
and this
return $this->belongsToMany('App\User', 'companies_managers', 'company_id', 'manager_id');
The IDs that I had set were not the correct ones for belongsToMany function
And this
$managers = Company::find($id)->managers();
was a problem too, was a dumb mistake of my part. I solved the return of Builder instance using just return instead of dd(), in that way I got the values I looking for. Thanks everyone!
I have a model Contract with properties 'id', 'orderer_user_id' and 'contractor_user_id'.
I have a model Signature with properties 'contract_id', 'user_id' and 'signed'.
I have a hasMany relationship on Contract to retrieve the Signatures belonging to the contract.
Each Contract has two Signatures, one belonging to the orderer, the other to the contractor.
I need to get all Contracts that have its orderer signatures not yet signed (so 'contract_id' has to be the id of its parent, 'user_id' has to be the 'orderer_user_id' of its parent and 'signed' has to be false)
What's the Laravel/Eloquent way to achieve this?
I understand I can just code a foreach loop and iterate all contracts, check its signatures and then build a collection of contracts with unsigned orderer signatures but it feels clumsy.
I've been playing around with relationships/has/doesnthave etc. but I can't seem to get the correct results.
You should have the relation implemented on Contract model
// Contract.php
public function signatures() {
// add proper parameters 2nd: foreign key and 3rd: local key if
// your Database design is not respecting laravel/eloquent naming guidelines
return $this->hasMany(Signature::class);
}
In order to retrieve the unsigned Contracts this should work:
$unsignedContracts = Contract::whereHas("signatures", '<', 2)->get();
I think this should also cover no entries at all, but in case it does not, you can also try this
$unsignedContracts = Contract::whereDoesntHave("signatures")
->orWhereHas("signatures", '<', 2)->get();
If you want to query all signatures with an additional condition this is also possible:
$unsignedContracts = Contract::whereHas("signatures", function($q) {
$q->where("signed","=",false);
})->get()
You can also introduce concrete relations for contractor and orderer in the Signature model:
// Signature.php
public function contractor() {
return $this->belongsTo(User::class, "contractor_user_id", "id");
}
public function orderer() {
return $this->belongsTo(User::class, "orderer_user_id", "id");
}
With these you should be able to do this:
// this should return all contracts where one of the
// required users has not signed yet
$unsignedContracts = Contract::where(function($q) {
$q->whereDoesntHave("contractor")
->orWhereDoesntHave("orderer");
})->get();
Laravel documentation is pretty nice imho, have a look on
https://laravel.com/docs/5.6/eloquent-relationships#querying-relations for more input.
You can either create a cope or define on your multiple relationship what you wish to be whenever you call it (add a ->where()->select()...).
Personally, I'd make a scope so you can just call the relationship whenever you want and just apply scopes whenever needed, making both functions (that's what they are in the end, functions) to be independent.
https://laravel.com/docs/5.6/eloquent#local-scopes
I have the following models in Eloquent: groups, threads, comments and users. I want to find all comments in a specific group from a specific user.
This is my current approach:
$group->threads->each(function ($thread) use ($user_id)
{
$user_comments = $thread->comments->filter(function ($comment) use ($user_id)
{
return $comment->owner_id == $id;
});
});
This looks ugly as hell, is probably slow as hell, and I just want to get rid of it. What is the fastest and most elegant way in Eloquent to get to my result set?
If a group hasMany threads, and a thread hasMany comments, you can add another relationship to group: group hasMany comments through threads.
On the group:
public function comments() {
return $this->hasManyThrough('Comment', 'Thread');
}
Now, you can get the comments in a group by $group->comments;
From here, you can tack on the requirement for the user:
$user_comments = $group->comments()->where('owner_id', $user_id)->get();
If you want, you can extract the where out into a scope on the Comment.
patricus solution pointed me in the right direction. I cross posted my question to the laracasts Forum and got a lot of help from Jarek Tkaczyk who also frequently visits this site.
hasManyThrough() for the Group model is the way to go:
public function comments()
{
return $this->hasManyThrough('ThreadComment', 'Thread');
}
There a couple of caveats, though:
Use the relation object instead of a collection ($group->comments(), NOT $group->comments)
If you use Laravel’s soft deletes you can’t just change the get() to a delete(), because you’ll get an ambiguity error for the column updated_at. You can’t prefix it either, it’s just how Eloquent works.
If you want to delete all comments from a specific user in a specific group you’ll have to do it a little bit differently:
$commentsToDelete = $group->comments()
->where('threads_comments.owner_id', $id)
->select('threads_comments.id')
->lists('id');
ThreadComment::whereIn('id', $commentsToDelete)->delete();
You basically fetch all relevant IDs in the first query and then batch delete them in a second one.
So I have a many to many relationship between Users and Photos via the pivot table user_photo. I use belongsToMany('Photo') in my User model. However the trouble here is that I have a dozen columns in my Photo table most I don't need (especially during a json response). So an example would be:
//Grab user #987's photos:
User::with('photos')->find(987);
//json output:
{
id: 987,
name: "John Appleseed",
photos: {
id: 5435433,
date: ...,
name: 'feelsgoodman.jpg',
....// other columns that I don't need
}
}
Is it possible to modify this method such that Photos model will only return the accepted columns (say specified by an array ['name', 'date'])?
User.php
public function photos()
{
return $this->belongsToMany('Photo');
}
Note: I only want to select specific columns when doing a User->belongsToMany->Photo only. When doing something like Photo::all(), yes I would want all the columns as normal.
EDIT: I've tried Get specific columns using "with()" function in Laravel Eloquent but the columns are still being selected. Also https://github.com/laravel/laravel/issues/2306
You can use belongsToMany with select operation using laravel relationship.
public function photos()
{
return $this->belongsToMany('Photo')->select(array('name', 'date'));
}
Im assuming you have a column named user_id. Then you should be able to do the following:
public function photos()
{
return $this->belongsToMany('Photo')->select(['id', 'user_id', 'date', 'name']);
}
You have to select, the foreign key, else it will have no way of joining it.
Specifying the exact columns you want for the Photos relationship will likely end up biting you in the butt in the future, should your application's needs ever change. A better solution would be to only specify the data you want to return in that particular instance, i.e. the specific JSON response you're delivering.
Option 1: extend/overwrite the toArray() Eloquent function (which is called by toJson()) and change the information returned by it. This will affect every call to these methods, though, so it may end up giving you the same problems as doing select() in the original query.
Option 2: Create a specific method for your JSON response and call it instead of the general toJson(). That method could then do any data building / array modifications necessary to achieve the specific output you need.
Option 3: If you're working with an API or ajax calls in general that need a specific format, consider using a library such as League/Fractal, which is built for just such an occasion. (Phil is also working on a book on building APIs, and it doesn't suck.)
This may be a dupe but I've been trawling for some time looking for a proper answer to this and haven't found one yet.
So essentially all I want to do is join two tables and attach a where condition to the entire collection based on a field from the joined table.
So lets say I have two tables:
users:
-id
-name
-email
-password
-etc
user_addresses:
-address_line1
-address_line2
-town
-city
-etc
For the sake of argument (realising this may not be the best example) - lets assume a user can have multiple address entries. Now, laravel/eloquent gives us a nice way of wrapping up conditions on a collection in the form of scopes, so we'll use one of them to define the filter.
So, if I want to get all the users with an address in smallville, I may create a scope and relationships as follows:
Users.php (model)
class users extends Eloquent{
public function addresses(){
return $this->belongsToMany('Address');
}
public function scopeSmallvilleResidents($query){
return $query->join('user_addresses', function($join) {
$join->on('user.id', '=', 'user_addresses.user_id');
})->where('user_addresses.town', '=', 'Smallville');
}
}
This works but its a bit ugly and it messes up my eloquent objects, since I no longer have a nice dynamic attribute containing users addresses, everything is just crammed into the user object.
I have tried various other things to get this to work, for example using a closure on the relationship looked promising:
//this just filters at the point of attaching the relationship so will display all users but only pull in the address where it matches
User::with(array('Addresses' => function($query){
$query->where('town', '=', 'Smallville');
}));
//This doesnt work at all
User::with('Addresses')->where('user_addresses.town', '=', 'Smallville');
So is there an 'Eloquent' way of applying where clauses to relationships in a way that filters the main collection and keeps my eloquent objects in tact? Or have I like so many others been spoiled by the elegant syntax of Eloquent to the point where I'm asking too much?
Note: I am aware that you can usually get round this by defining relationships in the other direction (e.g. accessing the address table first) but this is not always ideal and not what i am asking.
Thanks in advance for any help.
At this point, there is no means by which you can filter primary model based on a constraint in the related models.
That means, you can't get only Users who have user_address.town = 'Smallwille' in one swipe.
Personally I hope that this will get implemented soon because I can see a lot of people asking for it (including myself here).
The current workaround is messy, but it works:
$products = array();
$categories = Category::where('type', 'fruit')->get();
foreach($categories as $category)
{
$products = array_merge($products, $category->products);
}
return $products;
As stated in the question there is a way to filter the adresses first and then use eager loading to load the related users object. As so:
$addressFilter = Addresses::with('Users')->where('town', $keyword)->first();
$users= $addressFilter->users;
of course bind with belongsTo in the model.
///* And in case anyone reading wants to also use pre-filtered Users data you can pass a closure to the 'with'
$usersFilter = Addresses::with(array('Users' => function($query) use ($keyword){
$query->where('somefield', $keyword);
}))->where('town', $keyword)->first();
$myUsers = $usersFilter->users;