BelongsToMany relation with specific condition - laravel

I've the following tables:
users (list of users) :
id | type
5 | client
10 | expert
clients (assigning many users to many groups):
uid | gid
5 | 1
client_groups (groups defined by experts):
id | title | expert_uid
1 | diabetic | 10
Every expert can define a group of clients and put any of his clients in one of them.
A client may belong to many experts.
Now what I want is to get the group of the current user which is defined by specific expert.
I've tried the following relation:
class User{
public function client_groups()
{
return $this->belongsToMany(\App\Models\client_group::class,"clients","uid","gid");
}
}
User::with("client_groups")->
whereIn("id",$client_ids)->
orderby($orderBy,$order)->
get();
But as you may guess it will return all client_groups for the current client But I want the ones that has been defined by the current expert and not all of them.
Thanks in Advance

Related

How to find all items that have no related objects?

There are two related tables A and B. The relation is one to many - A may point to the multiple entities in B.
Example:
Table A
id | title
--------
1 | 'title 1'
2 | 'title 2'
Table B
id | id_from_a
--------
1 | 1
2 | 1
I want to find all entities in table A that do not have anything in table B using graphQL.
For time being I am using the following contraption:
query getData {
table_a(where: {_not: {table_b: {id_from_a: {_neq: -9999}}}}) {
id
title
}
}
It works, but it is ugly as hell, so I guess there should be some better graphql solution.

How can I remove duplicates results when using belongsToMany

Having the following tables:
----------- ----------------- ---------------
| PROJECT | | ACCESSES | | ENVIRONMENT |
----------- ----------------- ---------------
| id | | id | | id |
| title | | project_id | | title |
----------- | environment_id| ---------------
| username |
| password |
-----------------
My goal is to get all the environments used by a project through the accesses table
In my Project model:
public function environments(){
return $this->belongsToMany('App\Models\Environment', "accesses");
}
My problem is that if I have multiple rows with the same project_id and environment_id values in the accesses table, it will fetch multiple time the same environment.
How may I force it to retrieve each environment only once?
This is an old question, but the benefit of future travellers:
The distinct() method can help in this situation:
public function environments() {
return $this
->belongsToMany('App\Models\Environment', "accesses")
->distinct();
}
From the docs:
The distinct method allows you to force the query to return distinct results:
$users = DB::table('users')->distinct()->get();
As far as I can tell, this works at least as far back as Laravel 4.x, so it should be fine for all currently supported versions.
You can achieve this using sync method or toggle method it depends on your use case.
From the docs:
The many-to-many relationship also provides a toggle method which "toggles" the attachment status of the given IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached:
$project->environments()->toggle([1, 2, 3]);
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table
$project->environments()->sync([1, 2, 3]);
For more information please have a look in the docs.
https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships

Laravel's Eloquent. One/many to many of different models (types)

I've got a model that can be related to arbitrary number of items (other models). What is the best way to retrieve those as an array/collection of items of their types, e.g.
$basket = Basket::find(1);
dd($basket->items); // [Banana, Yoghurt, Bread, Bread, Ham, Cheese, Cheese]
Table: basket
| id | int |
| user_id | int |
Table: basket_items
| id | int |
| basket_id | int |
| item_id | int |
| item_type | string |
Models: Basket, Banana, Yoghurt, Bread, Ham, Cheese
Where I've got so far is: I can not use Eloquent's relations here since items method is referencing multiple models. The question is: can I (probably don't see how)?
As a plan-B I'd just implement that Basket::items method issuing a query and then fetching each and every model and hydrating them. I wonder if there a better way of dealing with that.

Laravel Relationship: a table having ids from two other tables

I have two tables: 'tours' and 'tourists' in my DB.
A 'tour' can have MANY 'tourist's, and 'tourist' can participate in MANY 'tour's.
So, I have successfully related them via 'begonsToMany" relationship (when adding rows to "tours' and 'tourists" an intermediate table 'tour_tourist' is given a row also.
"tour_tourist" table structure is:
tour_id | tourist_id
1 | 37
1 | 38
1 | 39
(tourists with id's 37, 38 and 39 go are assinged to the tour with id = 1)
THE PROBLEM : One of 'tourists' (37 or 38 or 39 from example abouve) can be a 'buyer' of the 'tour' (1 from above table). So only 1 person pays for the tour. Also this person can go to the tour/only pay for it. I pass this data (tour, tourists, who is buyer and does he goes to the tour) when submitting a tour via web-form.
So I want to create a 3rd table, called 'buyers' which represent a "tourist" who pays for the tour:
tour_id | tourist_id | is_tourist
1 | 39 | 0
(1. one 'tour_id' can match only ONE 'tourist_id')
(2. 'tourist_id' should be one of those who 'belong' to the 'tour_id' in the previous "tour_tourist" table - tourist 39 belongs to tour 1 - see table above).
(3. 'is_tourist' is 1/0, means the buyer goes to the tour/only pays, in my example it's 0 - he only pays, doesn't go).
I am wondering how can I do this using Eloquent relationships (one-to-one? hasManyThrough?) .
Appreciate any help.
Probably a simpler approach for that is to create two other columns called is_payer and is_tourist in your tour_tourist table in order to avoid creating your third table.
The result of your tour_tourist table could be something like this:
tour_id | tourist_id | is_payer | is_tourist
1 | 37 | 1 | 0/1
1 | 38 | 0 | 1
1 | 39 | 0 | 1
Then with eloquent you can simply access your extra columns' using withPivot method chaining your belongsToMany method.
For example, your Tour model can be something like this:
Tour
class Tour extends Eloquent {
protected $table = 'tours';
public function tourists() {
return $this->belongsToMany('Tourist')->withPivot('is_payer', 'is_tourist');
}
}
In the result you will have is_payer & is_tourist.
You can then filter them out using Collection methods.

Relationship Model in Laravel?

This question is about the Laravel style of doing things:
Everything in Laravel can be done in an elegant way.
I currently have a many to many relationship between mongrels and breeds through a table named breed_mongrel but this table also has a certainty value describing how certain the dog is that he's indeed a mix of that specific breed.
mongrel_id | breed_id | certainty|
----------------------------------
| 1 | 4 | 50 |
| 1 | 2 | 25 |
| 2 | 5 | 75 |
this means that mongrel#1 is 50% sure she's of breed#4 and 25% sure she's also a mix with breed#2. However mongrel#2 is a whooping 75% certain he is breed#5.
My question is what is the elegant way to add records to this table?
I could use something like this:
DB::table('breed_mongrel')->insert(
array('mongrel_id' => 3, 'breed_id' => 5, 'certainty' => 37));
But in Laravel I would normally do things more eloquently like:
$relation = new Relation;
$relation->breed_id = 1;
$relation->save();
But because it is a relationship and I can't follow the normal model named in singular camel caseform and DB table named in plural lower (snail) case I'm not sure what is Laravelly way to add entries to this database table?
You can use attach. It also accepts a second parameter allowing extra values to be added to the pivot table.
$mongrel = Mongrel::find(1);
$breed = Breed::find(4);
$mongrel->breeds()->attach($breed, array('certainty' => '50'));

Resources