简体   繁体   中英

Laravel eloquent inserting data only in Pivot table

Backround information

Using Laravel I'm building an application where I want to link a Company profile to a Station.

Company.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    protected $guarded = [];

    protected $table = 'companies';

    public function user()
    {
        return $this->hasMany('App\User');
    }

    public function station()
    {
        return $this->belongsToMany('App\Station')->withPivot('company_stations');
    }

    public function line()
    {
        return $this->belongsToMany('App\Line');
    }
}

Station.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Station extends Model
{
    protected $guarded = [];

    protected $table = 'stations';

    public function lines()
    {
        return $this->belongsToMany('App\Line');
    }

    public function company()
    {
        return $this->belongsToMany('App\Company')->withPivot('company_stations');
    }
}

company_stations migration

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

class CreateCompanyStationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('company_stations', function (Blueprint $table) {
            $table->id();
            $table->integer('company_id')->unsigned();
            $table->integer('station_id')->unsigned();
            $table->boolean('following')->default(false);
            $table->boolean('completed')->default(false);
            $table->timestamps();
        });
    }

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

I also have a migration company_stations, but no Model for it.

The question

I want to create a checkbox on the station view where the currently logged in Company ID is linked to the Station ID in the pivot table to keep track of which stations the company is following and wether the company has completed that station or not.

What would be the easiest and most clean approach to this? Do I make a new Model CompanyStation + controller or can this be filled in from the Company or Station controller?

You can use sync method of belongsTomany relationship.

$station = Station::find($stationid);

$station->company()->sync([1,2,3]); //1,2,3 is the company ids which you're selection through checkbox.

//this will drop all the existing companies except the companies with id 1,2,3. If these ids don't exist it will attach them (still dropping the existing ones).

if you add a column to your piviot table company_stations example: 'completed' you can access it with

foreach ($company->stations as $station) {
    dd($station->pivot->completed);
}

you can add that data via

$company->stations()->attach($station->id, ['completed' => true]);

Query it //only show me completed company stations. (from piviot)

Company::whereHas('stations', function($q) {
    $q->where('company_stations.completed', true);
})
->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM