我试图从user_trips表中获取用户(ID 1)的旅行数据,以及user_flights表中的旅行航班,并使用airportsname外键获取flight_fromflight_to
我尝试了很多方法,我想这很容易,但这是我的第一个拉维尔项目。我读过文件,看过拉拉队比赛,但我就是想不出合适的组合。
$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');
});

TripBuilder控制器
<?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;
    }
}

用户航班模型
<?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时,它包含您指定的任何急切加载的模型。

08-06 19:18