【问题标题】:How to create query with twice a connection to a table in Laravel 5.3?如何在 Laravel 5.3 中创建两次连接到表的查询?
【发布时间】:2017-07-19 19:09:22
【问题描述】:

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

例如:

城市表:

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

在模型中:from_cityTHR 并且 to_cityLON

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 名称。

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

如何创建这个查询?

【问题讨论】:

    标签: php mysql laravel eloquent laravel-5.3


    【解决方案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();
    }
    

    【讨论】:

      【解决方案2】:

      您也可以使用 eloquent 模型来定义关系。

      更多详情请访问https://laravel.com/docs/5.3/eloquent-relationships

      箱子两个模型-- 第一个是“航班”

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

      第二个模型是“城市”

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

      现在开始获取

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

      【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2019-06-10
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      相关资源
      最近更新 更多