Laravel 5.4不会同步模型

时间:2018-09-25 00:50:06

标签: model eloquent laravel-5.4

我正在尝试获得两个具有已定义关系的模型进行同步,但是当尝试进行同步时,方程式的一侧为空白。

一个模型的主键不是通常的约定,但是我已经在关系和$ primaryKey下的模型中定义了这个主键。

模型一(LinesCompany):

class LinesCompany extends Model
{
    protected $table = 'lines_companies';
    protected $primaryKey = 'participant_id';

    public $incrementing = false;

    public function fuel()
    {
        return $this->belongsToMany(Fuel::class, 'fuel_lines_company', 'participant_id', 'fuel_id');
    }
}

第二个模型(燃油):

class Fuel extends Model
{
    public function linesCompany()
    {
        return $this->belongsToMany(LinesCompany::class, 'fuel_lines_company', 'fuel_id', 'participant_id');
    }
}

表格(加油站公司):

id (primary) | fuel_id (foreign) | participant_id (foreign points to lines_companies table)

代码:

public function addLinesCompany(Request $request, $linesCompany)
{
    $LinesCompany = new LinesCompany;
    $LinesCompany->participant_id = $linesCompany;
    $LinesCompany->code = $request->get('linesCode');
    $LinesCompany->geography = $request->get('geo');
    $LinesCompany->website = $request->get('web');
    $LinesCompany->emergency_number = $request->get('phone');
    $LinesCompany->review_process = $request->get('review');

    try{
        DB::beginTransaction();

        $LinesCompany->save();

        $LinesCompany->id = $LinesCompany->participant_id;

        $LinesCompany->fuel()->sync($request->get('linesFuel'));

        DB::commit();

        return true;

    } catch(PDOException $e){
        DB::rollback();

        return 'An error occured adding the Lines Company.';
    }
}

异常消息:

(3/3) QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'participant_id' cannot be null (SQL: insert into `fuel_lines_company` (`fuel_id`, `participant_id`) values (2, ))

希望有人可以看到我要去哪里解决这个问题。

谢谢

0 个答案:

没有答案