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

a 夏天 提交于 2019-11-29 15:55:45

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();
}

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!