、私はそれが親のまっすぐ前方ケースだと思う - 子。
ここではBaseReport
またはReport
が親モデルであり、WantedReport
とMissingReport
は子供です。
ダイアグラムで変更する必要があるのは、基本レポートテーブルの親レコードを指すように子テーブルにreport_id
という外部キーを定義する必要があることだけです。
Table-reports
id // primary key
date
description
Table - wanted_reports
id //primary key
report_id //foreign key linking to the reports table
status_at
is_captured //maybe a boolean field
charge
Table - missing_reports
id //primary key
report_id //foreign key linking to the reports table
status_at
is_found
last_seen_date
last_seen_at
ザ・あなたはとして対応するモデルを定義することができます - をレポート
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Report extends Model
{
protected $table = 'reports';
protected $fillable = ['report_date', 'description'];
public function wanted_reports()
{
return $this->hasMany(WantedReport::class);
}
public function missing_reports()
{
return $this->hasMany(MissingReport::class);
}
}
WantedReport
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class WantedReport extends Model
{
protected $table = 'wanted_reports';
protected $fillable = ['report_id', 'status_at', 'is_captured', 'charge'];
public function report()
{
return $this->belongsTo(Report::class);
}
}
MissingReport
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class MissingReport extends Model
{
protected $table = 'missing_reports';
protected $fillable = ['report_id', 'status_at', 'is_found', 'last_seen_date', 'last_seen_at];
public function report()
{
return $this->belongsTo(Report::class);
}
}
あなたが通常行うように次にどこでもあなたのアプリケーションにあなたが関係をアクセスすることができ、例えば
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ReportsController
{
public function store(Request $$request)
{
$report = $this->model->create([
'report_date' => Carbon:::now(),
'description' => $request->get('description')
]);
if($report)
{
$wantedReport = $report->wanted_reports()->create([
'status_at' => $request->get('status'),
...
]);
$missingReport = $report->missing_reports()->create([
'status_at' => $request->get('status'),
...
]);
}
}
}
希望これは
おかげ@Donkamashに役立ちます。これは非常に意味があり、非常に簡潔です。しかし、それぞれのwanted_reportとmissing_reportは1つのレポートにしか関係しないので、これが正しいかどうかはわかりません。'public function missing_reports() { return $ this-> hasMany(MissingReport :: class); } 'また、私はまだ多態性の関係ではない理由を理解するのに苦労しています。限り、私は多態性を明示的に外部キーを維持する必要性を排除することができます。私はまだこれらの概念の周りに私の頭を包んでいるので、私に同行してください –
それは1対1の関係であれば、それに応じてあなたの関係を定義することができます 'public function missing_reports(){return $ this-> hasOne(MissingReport :: class ); } '。あなたのケースでは多態性の関係は必要ありません。また、多態性の関係ではクエリの実行中に追加のテーブル参照が必要なので、必要でない場合は使用しないでください。しかし、再びそれはあなたの好みに依存します。 – Donkarnash
ありがとうございます。これを実装しましょう。私はあなたの答えを受け入れる傾向がありますが、最初に私がそれが欲しいのと同じように実際に動作することを確認させてください。 –