没有将id传递给Laravel中的模型

时间:2016-08-25 17:24:43

标签: php mysql laravel eloquent

我使用Eloquent的firstOrCreate()方法来插入我的数据,或检索它是否存在。

我需要获得$trip->id。如果我在FlightController中echo,那么它echo是正确的id,但它似乎没有将其传递到UserFlights模型中以插入user_flights

我在页面上收到此错误:

  

Connection.php第729行中的QueryException:SQLSTATE [23000]:完整性   约束违规:1048列'user_trips_id'不能为空(SQL:   插入user_flightsairport_fromairport_to,   user_trips_id)值(1,4,))

流程:用户从下拉框(<select>)中选择两个机场(飞行并飞往)并将其添加到“旅行”中。如果他们没有旅行,它会创建一个,然后将两个机场添加到他们的旅行中。

模式

# `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('trip_id')->unsigned();
     $table->integer('airport_from')->unsigned();
     $table->integer('airport_to')->unsigned();
     $table->foreign('trip_id')->references('id')->on('user_trips')->onDelete('cascade');
});

FlightController

<?php

namespace App\Http\Controllers;

use App\UserFlights;
use App\UserTrips;
use Illuminate\Http\Request;

/**
 * Class FlightController
 *
 * @package App\Http\Controllers
 */
class FlightController extends Controller
{
    /**
     * @param Request $request
     * @param UserTrips $user_trips_obj
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request, UserTrips $user_trips_obj)
    {
        // Retrieve the trip by the attributes, or create it if it doesn't exist...
        $trip=$user_trips_obj->addTrip();

        # Returns the ID correctly.
        //echo $trip->id;exit;

        $user_trips_obj->addFlight(
            new UserFlights([
                'airport_from'=>$request->flight_from,
                'airport_to'=>$request->flight_to,
                # Does not pass the `$trip->id` into the UserFlights model.
                'user_trips_id'=>$trip->id
            ])
        );

        return back();
    }
}

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('App\UserFlights');
    }

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

    /**
     * @return mixed
     */
    public function addTrip()
    {
        // Retrieve the trip by the attributes, or create it if it doesn't exist...
        $trip=$this->firstOrCreate([
            'user_id'=>1,
            'name'=>'My Trip'
        ]);

        return $trip;
    }
}

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=[
        'airport_from',
        'airport_to',
        'user_trips_id'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function usertrips()
    {
        return $this->belongsTo('App\UserTrips');
    }
}

1 个答案:

答案 0 :(得分:1)

您的addFlight()方法调用$this->userflights()->save($user_flights_obj);

当您在关系对象上调用save()时,它会将传入的对象($user_flights_obj)上的外键设置为拥有该关系的对象的id($this) 。然后它保存$user_flights_obj对象。

由于您的控制器调用$user_trips_obj->addFlight(new UserFlights...)$this方法中的addFlight()引用正在引用控制器中的$user_trips_obj实例。这个实例只是一个空shell,空白id。因此,在addFlight()方法中,当您在关系上调用save()时,它会将新UserFlights实例上的外键设置为{{{ 1}}被称为(空白)。

要解决此问题,您只需要在控制器中创建的addFlight()实例上调用addFlight()即可。这是您要将新$trip实例关联到的实例。此外,您不需要手动设置外键;这就是在关系上调用UserFlights的全部原因。