php - 查询链接多个表

标签 php mysql laravel eloquent

我正在尝试从 user_trips 表中获取用户 (ID 1) 旅行数据,以及 user_flights 表中的旅行航类,我正在获取airports.name 使用 flight_fromflight_to 外键。

我尝试了很多方法,我认为这很简单,但这是我的第一个 Laravel 项目。我已阅读文档并观看了 LaraCasts,但我就是想不出正确的组合。

$user_flights 变量返回:

[
    {
        "id":1,
        "user_trips_id":6,
        "flight_from":1,
        "flight_to":14,
        "flight from":
        {
            "id":1,
            "code":"AIZ",
            "name":"Lee C Fine Memorial",
            "city":"Lake Of The Ozarks",
            "country":"United States"
        },
        "flightto":
        {
            "id":14,
            "code":"AEX",
            "name":"Alexandria Intl Arpt",
            "city":"Alexandria",
            "country":"United States"
        }
    },
    {
        "id":2,
        "user_trips_id":7,
        "flight_from":1,
        "flight_to":22,
        "flight from":
        {
            "id":1,
            "code":"AIZ",
            "name":"Lee C Fine Memorial",
            "city":"Lake Of The Ozarks",
            "country":"United States"
        },
        "flightto":
        {
            "id":22,
            "code":"ADG",
            "name":"Lenawee County Arpt",
            "city":"Adrian",
            "country":"United States"
        }
    }
]

我需要它返回这样的东西(我认为):

[
    {
        "id":6,
        "user_id":1,
        "name":"My Trip",
        "flights":
        {
            "id":1,
            "user_trips_id":6,
            "flight_from":1,
            "flight_to":14,
            "flight from":
            {
                "id":1,
                "code":"AIZ",
                "name":"Lee C Fine Memorial",
                "city":"Lake Of The Ozarks",
                "country":"United States"
            },
            "flightto":
            {
                "id":14,
                "code":"AEX",
                "name":"Alexandria Intl Arpt",
                "city":"Alexandria",
                "country":"United States"
            }
        }
    }
]

架构

# `user_trips` table
Schema::create('user_trips', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('user_id')->unsigned()->index();
     $table->text('name');
});
# `user_flights` table
Schema::create('user_flights', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('user_trips_id')->unsigned();
     $table->integer('flight_from')->unsigned();
     $table->integer('flight_to')->unsigned();
     $table->foreign('user_trips_id')->references('id')->on('user_trips')->onDelete('cascade');
     $table->foreign('flight_from')->references('id')->on('airports')->onDelete('cascade');
     $table->foreign('flight_to')->references('id')->on('airports')->onDelete('cascade');
});

TripBuilderController

<?php
namespace App\Http\Controllers;

use App\Airport;
use App\UserFlights;

/**
 * Class TripBuilderController
 *
 * @package App\Http\Controllers
 */
class TripBuilderController extends Controller
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $airports=Airport::all();

        # Returns all `user_trips` and `user_flights`.
        #    I need to return only `user_trips`.`user_id` associated to user ID 1,
        #    and the `user_flights` associated to the user's `user_trips`.
        $user_flights=UserFlights::with('flightfrom')->with('flightto')->get();

        return view('welcome', compact('airports', 'user_flights'));
    }
}

UserTrips 模型

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class UserTrips
 *
 */
class UserTrips extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps=FALSE;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable=[
        'name',
        'user_id'
    ];

    /**
     * @param UserFlights $user_flights_obj
     * @return Model
     */
    public function addFlight(UserFlights $user_flights_obj)
    {
        return $this->userflights()->save($user_flights_obj);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userflights()
    {
        return $this->hasMany(UserFlights::class);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * @return mixed
     */
    public function addTrip()
    {
        # Retrieve the trip by the attributes, or instantiate a new instance...
        $trip_obj=$this->firstOrNew(['user_id'=>1]);
        if(!$trip_obj->id)
        {
            $trip_obj->name='My Trip';
            $trip_obj->save();
        }

        return $trip_obj;
    }
}

UserFlights 模型

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class UserFlights
 *
 */
class UserFlights extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps=FALSE;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable=[
        'flight_from',
        'flight_to'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function flightfrom()
    {
        return $this->belongsTo(Airport::class, 'flight_from');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function flightto()
    {
        return $this->belongsTo(Airport::class, 'flight_to');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function usertrip()
    {
        return $this->belongsTo(UserTrips::class, 'user_trips_id');
    }
}

最佳答案

User::find(1)->userTrips()->with('userflights', 'userflights.flightfrom', 'userflights.flightto')->get();

或直接从 UserTrips

调用
UserTrips::whereUserId(1)->with('userflights', 'userflights.flightfrom', 'userflights.flightto')->get();

with() 给你 eager loading当您将模型转换为 JSON 时,它包括您指定的任何预先加载的模型。

关于php - 查询链接多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39175483/

相关文章:

php - "The page has expired due to inactivity"- Laravel 5.5

css - 在 Laravel 中找不到带有 font-face 的字体

php - 创建具有所有 NULL 值的关联数组的最简洁方法是什么?

mysql - MySQL 到 H2 DDL 的问题

java - 如何在 mysql 中选择几个相同的数据之一并在 jComboBox java 中查看?

php - 在php mysql中显示类别和子类别

php - 在 Laravel 中获取 foreach 循环中的所有文件

php - 疯狂的 xhr 错误

javascript - 在订阅表单中获取名称字段的字母数字字符串

javascript - 如何使用从单选按钮在页面中选择的数据从 HTML 页面发送电子邮件?