gpt4 book ai didi

php - 如何在 Laravel 5.3 中创建两次连接到表的查询?

转载 作者:行者123 更新时间:2023-11-29 01:36:18 25 4
gpt4 key购买 nike

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

例如:

城市表:

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

在模型中:from_cityTHRto_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 名称。

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

如何创建这个查询?

最佳答案

您还可以使用 Eloquent 模型来定义关系。

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

crate 两种模型 --第一个是“航类”

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

关于php - 如何在 Laravel 5.3 中创建两次连接到表的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42515089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com