Yura
Yura

Reputation: 2248

How to do hasMany and belongsToMany at same model?

I have 2 models, Employee & FieldReport. I need to create relations based on the following conditions:

Field report is owned by an employee whose character is absolute (owner's data must be displayed and cannot be edited), where the report field also has a tag to mark who the employees are in that report field.

An employee, himself, has many field reports.

For now, I've made a relationship, something like this:

  1. Employee has many Field Reports.
  2. Employee belongs to many Field Reports.
  3. Field Report belongs to Employee.
  4. Field Report belongs to many Employees.

Then I have a problem where PHP doesn't allow the same method name (in the Employee model). Example:

Whereas if I define the function name custom, I cannot get the value to fill the first pivot column and generate an error like the following:

SQLSTATE [23000]: Integrity constraint violation: 19 NOT NULL constraint failed: field_report_participant.field_report_id (SQL: insert into "field_report_participant" ("id", "participant_id") values ​​(1, 2))

Is there any solution? This is how my scripts looks like:

Employee.php


/**
 * Each employee has many fieldReports.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\HasMany
 */
public function fieldReports()
{
    return $this->hasMany(FieldReport::class);
}

/**
 * Each employee belongs to many fieldReports.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\BelongsToMany
 */
public function fieldReports()
{
    return $this->belongsToMany(FieldReport::class);
}

FieldReportController.php

/**
 * Store a newly created resource in storage.
 *
 * @param  \App\Http\Requests\RequestFieldReport  $request
 * @return \Illuminate\Http\Response
 */
public function store(RequestFieldReport $request)
{
    $fieldReport = $this->data($request, $this->storeImages($request));

    $fieldReport->participants()->sync(
        $request->participants
    );

    return response()->json([
        'created' => true,
        'data' => $fieldReport,
    ], 201);
}

FieldReport.php

/**
 * Each field report belongs to a company.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\BelongsTo
 */
public function company()
{
    return $this->belongsTo(Company::class);
}

/**
 * Each field report belongs to a employee.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\BelongsTo
 */
public function employee()
{
    return $this->belongsTo(Employee::class);
}

/**
 * Each field report belongs to many participants.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\BelongsToMany
 */
public function participants()
{
    return $this->belongsToMany(Employee::class, 'field_report_participant', 'participant_id', 'id');
}

create_field_reports_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFieldReportsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('field_reports', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('company_id');
            $table->bigInteger('employee_id');
            $table->string('title', 100);
            $table->text('chronology');
            $table->json('images')->nullable();
            $table->timestamp('closed_at')->nullable();
            $table->string('closed_by', 100)->nullable();
            $table->timestamp('opened_at')->nullable();
            $table->string('opened_by', 100)->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('field_reports');
    }
}

field_report_participant_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFieldReportParticipantTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('field_report_participant', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('field_report_id');
            $table->bigInteger('participant_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('field_report_participant');
    }
}

Upvotes: 0

Views: 102

Answers (1)

Yura
Yura

Reputation: 2248

After an hour pulling off my hair, trying to do a backflip and asked on each different forums, finally I had the answer. Unfortunately, he has no account on this forum and can't give the answer for this question.

The problem is I put a wrong key on the participants method which causing the field_report_id placed in a wrong place, in this case; id. Which is solved by doing this:

/**
 * Each field report belongs to many participants.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\BelongsToMany
 */
public function participants()
{
    return $this->belongsToMany(Employee::class, 'field_report_participant', 'field_report_id', 'participant_id');
}

And then, on the Employee class, I could create exactly different method and link it with the pivot table. Like this:

/**
 * Each employee belongs to many assignedFieldReports.
 *
 * @return \Illuminate\Database\Eloquent\Relationship\BelongsToMany
 */
public function assignedFieldReports()
{
    return $this->belongsToMany(FieldReport::class, 'field_report_participant', 'participant_id', 'field_report_id');
}

Hopefully, it can help someone facing this exact same issue on the future.

Upvotes: 1

Related Questions