How to create query with twice a connection to a table in Laravel 5.3?

前端 未结 2 455
粉色の甜心
粉色の甜心 2020-12-21 12:07

I need get two city names with one query:

For example:

City table:

+---------+----------+
|  Pana   |   Name   |
+---------+----------+
|   T         


        
相关标签:
2条回答
  • 2020-12-21 12:20

    With straight SQL you could give each joined table an alias - e.g.

    SELECT flights.*
    FROM flights as f
     JOIN cities as fromCity on fromCity.pana = f.from_city
     JOIN cities as toCity on toCity.pana = f.to_city
    WHERE f.id = 3 --
    

    With Eloquent, use select() to specify select fields. Also use DB::raw() to use raw SQL (e.g. giving an alias to table like DB::raw('cities as toCity').

    public function scopePrintQuery($query, $id)
    {
      $join = $query
        -> join(DB::raw('cities as fromCity'), 'fromCity.pana', 'flights.from_city')
        -> join(DB::raw('cities as toCity'), 'toCity.pana', 'flights.to_city')
        -> where('flights.id', $id)
        ->select([
            'flights.*',
            DB::raw('fromCity.name as from_city')
            DB::raw('toCity.name as to_city')
        ]);
        return $join->get();
    }
    
    0 讨论(0)
  • 2020-12-21 12:44

    you can also use the eloquent model with defining the relationship.

    Also for more detail visit https://laravel.com/docs/5.3/eloquent-relationships

    crate two model -- 1st is "Flights"

    <?php
    
    
    class Flights extends Model
    {
        protected $table = 'flights';
    
        /**
         * Get the From City detail.
         */
        public function fromCity()
        {
            return $this->hasOne('App\Models\City', 'Pana', 'from_city');
        }
    
        /**
         * Get the To city state.
         */
       public function toCity()
       {
            return $this->hasOne('App\Models\City', 'Pana', 'to_city');
       }
    
    }
    

    2nd Model is "City"

    <?php
    class City extends Model
    {
        protected $table = 'city';
    }
    

    Now for fetching

    Flights::where(id, $id)->with('toCity', 'fromCity')->get();
    
    0 讨论(0)
提交回复
热议问题