php - 不将 id 传递给 Laravel 中的模型

标签 php mysql laravel eloquent

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

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

我在页面上收到此错误:

QueryException in Connection.php line 729: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_trips_id' cannot be null (SQL: insert into user_flights (airport_from, airport_to, user_trips_id) values (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');
});

飞行 Controller

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

最佳答案

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

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

由于您的 Controller 调用了 $user_trips_obj->addFlight(new UserFlights...) , $this在你的内部引用 addFlight()方法引用 $user_trips_obj来自您的 Controller 的实例。这个实例只是一个空壳,id 为空。因此,在你的 addFlight() 里面方法,当你调用 save()在关系上,它将在您的新 UserFlights 上设置外键instance 到 addFlight() 所在实例的 id被称为(空白)。

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

关于php - 不将 id 传递给 Laravel 中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39151298/

相关文章:

php - 为一次性下载存储文件

sql - 为什么 IN 条件会比 sql 中的 "="慢?

php - Laravel Route [dashboard] 未定义

laravel - "except"和 "idColumn"在 "unique:table,column,except,idColumn"中指的是什么?来自 Laravel 文档

php - 检查字符串是否为unix时间戳

php - drupal 搜索 api solr 索引中缺少字段

mysql - 如何在 Rails 中编写代码以在 SQL 中运行我想要的查询

php - 如何在 Laravel 5.8 中使用 IF 和 ELSE 检查 mysql 表 NULL 或 NOT?

PHP PDO 扩展不适用于 IIS

PHP PNG 24 位透明透明