繁体   English   中英

Laravel eloquent 仅在 Pivot 表中插入数据

[英]Laravel eloquent inserting data only in Pivot table

背景资料

使用 Laravel 我正在构建一个应用程序,我想将公司资料链接到工作站。

公司.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 迁移

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

我也有一个迁移 company_stations,但没有 Model。

问题

我想在站点视图上创建一个复选框,其中当前登录的公司 ID 链接到 pivot 表中的站点 ID,以跟踪公司关注的站点以及公司是否已完成该站点。

什么是最简单和最干净的方法? 我是做一个新的 Model CompanyStation + controller 还是可以从 Company 或 Station controller 填写?

您可以使用belongsTomany关系的sync method

$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).

如果您在数据透视表 company_stations 示例中添加一列:“已完成”,您可以使用

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

您可以通过添加该数据

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

查询它//只显示已完成的公司站。 (来自枢轴)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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