Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel join tables

Tags:

join

php

laravel

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.

like image 720
Jensej Avatar asked Dec 13 '14 13:12

Jensej


People also ask

What is join in laravel?

Laravel Cross Join Clause: The Laravel Cross Join clause allows every row from Table 1 to join with every row from Table 2. Laravel Advanced Join Clauses: In this clause, other functionalities can be included into the command set. Queries like “where” and “orwhere” can be used to compare column with values.

How do you make a relation between two tables in laravel?

To define a relationship, we need first to define the post() method in User model. In the post() method, we need to implement the hasOne() method that returns the result. Let's understand the one to one relationship through an example. First, we add the new column (user_id) in an existing table named as posts.


1 Answers

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.

like image 132
Khan Shahrukh Avatar answered Oct 08 '22 18:10

Khan Shahrukh