如何创建与Laravel 5.3中的表连接两次的查询?

时间:2017-02-28 17:24:12

标签: php mysql laravel eloquent laravel-5.3

我需要通过一个查询获得两个城市名称:

例如:

城市表:

+---------+----------+
|  Pana   |   Name   |
+---------+----------+
|   THR   |  Tehran  |
|   LON   |  London  |
+---------+----------+

在模型中: from_city THR to_city LON

public function scopePrintQuery($query, $id)
{
    $join = $query
        -> join('cities', 'cities.pana', 'flights.from_city')
        -> join('cities', 'cities.pana', 'flights.to_city')
        -> where('flights.id', $id)
        ->get([
            'flights.*',
            'cities.name as from_city'
            ??? for to_city?
        ]);
    return $join;
}

现在,我需要在此查询中获取 from_city 名称和 to_city 名称。

查询不适用于来自一个表的两个连接!

如何创建此查询?

2 个答案:

答案 0 :(得分:3)

你也可以使用雄辩的模型来定义关系。

有关详细信息,请访问https://laravel.com/docs/5.3/eloquent-relationships

crate两个模型 - 第一个是#34;航班"

<?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');
   }

}

第二模型是&#34;城市&#34;

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

现在提取

Flights::where(id, $id)->with('toCity', 'fromCity')->get();

答案 1 :(得分:1)

使用直接SQL,您可以为每个连接表添加别名 - 例如

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 --

使用Eloquent,使用select()指定选择字段。还可以使用DB::raw()来使用原始SQL(例如,为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();
}