Laravel join tables - php

I have 2 tables and I need to join those tables.
I need to select id and name from galleries, where share gal.id = galleries.id and user_id = auth::id().
Tables:
Galleries: id, name
Share: gal_id, user_id
Please show me example in laravel. And I need to display it.

To achieve this, you have Relationship in Eloquent ORM. The official website states :
Of course, your database tables are probably related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy. Laravel supports many types of relationships:
You can read all about eloquent relationship over here
If you do not want to use relationship, following is an example on how to join two tables :
DB::table('users')
->select('users.id','users.name','profiles.photo')
->join('profiles','profiles.id','=','users.id')
->where(['something' => 'something', 'otherThing' => 'otherThing'])
->get();
The above query will join two tables namely users and profiles on the basis of user.id = profile.id with two different conditions, you may or may not use where clause, that totally depends on what you are trying to achieve.

Related

Optimal way to find intersection in Laravel

I have User and Chat model in Laravel app. User can be member in many chats so I have many-to-many relation between chats and users - belongsToMany is used.
Let's say I know few user IDs and I want to retrieve all common chats (chats where they are members at the same time, e.g., group chats where all the users with the given IDs are grouped in). How this query should be build using Laravel?
The most optimal way would be to do a join:
Chat::join('chat_user', 'chat_id', 'chats.id')
->whereIn('chat_user.user_id',$listOfUserIds)
->selectRaw('chat_user.chat_id, COUNT(1) as users_count')
->groupBy('chat_user.chat_id')
->having('users_count','=', count($listOfUserIds));
This is optimal because it only joins the pivot.
The elegant way to do this though is to use whereHas with the "cardinality" parameters, i.e., find all chats which those users are involved in as long as all of them are involved.
Chat::whereHas('user', function ($q) {
return $q->whereIn('id', $listOfUserIds);
}, '=', count($listOfUserIds));
this still only does one query but joins the pivot and the users table.
You can use:
$membersWithChats = Member::whereIn('id', $listOfIDs)->with('chats')->get();

Tinder Laravel matching between 2 models

i have 2 tables namely users and employers . I would like to match them together like tinder style, which means that when both the user and the employer liked each other , they will each receive a notification .
However i am not sure how would the relationship table will look like??
Right now what i have is in the Relationship Table ,
1.user_id
2.target_employer_id
3.employer_id
4.target_user_id
If i am not wrong , this is considered as a Many - Many relationship.
So , is this table correct???
As I understand your question, in your application, a user can like an employer, and an employer can like a user.
If this is right, it seems clear to me that there are two distinct (many to many) relationships (user => employer, employer => user), and that in your proposed table only two fields are filled at a time.
The best way to represent those relationships is to use two tables.
User to employer fields:
user_id
target_employer_id
Employer to user fields:
employer_id
target_user_id
Depending if you are using Laravel 4 or Laravel 5, you can use one of those two packages to generate the two pivot tables via a migration:
https://github.com/JeffreyWay/Laravel-4-Generators
https://github.com/laracasts/Laravel-5-Generators-Extended

Fuel PHP Orm, join

I have been playing with fuelphp lately and am trying something with the ORM.
Never used an ORM before so I think I don't understand very well.
My database consists of object types with multiple objects meta´s.
So I have three tables.
object_types which has multiple object_types_meta which is a join table to objects_meta_type
But I don't know how to convert this to the ORM. Can someone please point me in the correct direction?
I thought it would be:
object_types has many object_types_meta and then object_types_meta belongs to objects_types but what do I do with object_meta_type?
Thanks in advance!
It looks like you may be using a many to many relationship with object_types_meta being the in between table?
http://fuelphp.com/docs/packages/orm/relations/many_many.html
If the join table doesn't contain any extra columns except the two foreign keys, you should use a many-many relation, and use the join table as 'through' table.
If it does contain columns you need to access, you have to create a model for the join table too, and create two one-to-many relations from the join table to the two other models.

MVC Complex query and model usage

I have 3 tables.
users,
campaigns,
links.
They have one-to-many relations. User have many campaigns. Campaign has many links.
I calculate top users by counting the total number of links each user have. So I join 3 tables and group by user and select user and sum(links).
This query involves 3 tables. I have already 3 model class for each of these tables. Now my question is in which model should I put this query? should it go in User model (as I call it top10users? Or there is other way to get this info by utilizing already existing 3 models. I want to know what is most suitable from MVC's point of view.
Additional Information
I am using orm in kohana.
Query:
SELECT u.id,
u.name,
SUM(l.num_visited) total_num_visited
FROM users u
JOIN campaigns c
ON ( u.id = c.user_id )
JOIN links l
ON ( c.id = l.campaign_id )
GROUP BY u.id
ORDER BY total_num_visited DESC
LIMIT 10;
There's no strict reason that your model absolutely has to map 1-to-1 with a table. It may make the most sense in this case to provide a model specifically for Top Users, especially because it is dependent on joining data from several related tables.
Then if there is specific business logic related to Top Users that isn't relevant to the standard User class, you can keep it separated and clean. You can always provide helper / factory methods from TopUser that return instances of User, Campaign, or Link if you need to drill down.
I would say go for topusers(). There is no "correct" answer to this question, not in a technical context. But it should be clearly to understand. So if you want to get top users, why would you put such a method in one of the other models than users? Think of a new team member who gets your code: Where would you look for top users when not in the users model first?

Using Yii relational query

Is it possible while defining a related Model in an ActiveRecord definition to specify a relation scope that allows only those models to be related whose corresponding column(s) match some predefined critaria in the joining table ?
eg. let us have a users table with fields : id(pk), username(pk),pwd_hash(text), pwd_salt(text)
and an items table : id(pk), itemData(text)
and a correlating table : id(pk),user_id(pk), item_id(pk), some_attribute(int)
Now I would like to define a Many-to-Many relationship such that User Model has a field xitems which would provide me only those items for which the value of some_attribute is greater than some value y. Is it possible to do so using Yii ActiveRecord implementation.
I do understand that I can define a model corresponding to the correlating table which would have belongs-to relation with both items and users and query this table ... but I was looking for a more succinct approach.
[edit]
Probably my best bet would be define a model method which abstracts an inner join operation.
I'm fairly sure you do need a model for the join table to get access to its data, which your example needs. Without the join table model, AR will only deal with the FKs in the join table (AFAIK).
This article may be of help to you: Accessing data in a join table with the related models

Categories