【发布时间】:2020-10-21 19:34:11
【问题描述】:
背景信息
我正在使用 Laravel 构建一个应用程序,我想将公司资料链接到工作站。
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 迁移
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,但没有模型。
问题
我想在站点视图上创建一个复选框,将当前登录的公司 ID 链接到数据透视表中的站点 ID,以跟踪公司关注的站点以及公司是否已完成该站点.
什么是最简单和最干净的方法?我是做一个新的型号CompanyStation+控制器还是可以从公司或站控制器填写?
【问题讨论】:
标签: php laravel eloquent pivot