【发布时间】:2021-05-07 12:16:01
【问题描述】:
我正在为我的网站制作警报,我决定使用 Alarmable 模型作为轴承模型,而不仅仅是一个辅助表。
警报看起来像这样
Schema::create('alarms', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('common_interval')->nullable();
$table->timestamps();
});
还有像这样的警报
Schema::create('alarmables', function (Blueprint $table) {
$table->id();
$table->foreignId('alarm_id');
$table->nullableMorphs('alarmable');
$table->date('date');
$table->foreignId('machine_counter_id')->nullable();
$table->date('next_date')->nullable();
$table->integer('next_counter')->nullable();
$table->text('note')->nullable();
$table->nullableMorphs('executed_by');
$table->foreignId('submitted_by');
$table->timestamps();
$table->foreign('alarm_id')
->references('id')
->on('alarms');
$table->foreign('submitted_by')
->references('id')
->on('users')
->onDelete('set null');
$table->foreign('machine_counter_id')
->references('id')
->on('machine_counters')
->onDelete('set null');
});
到目前为止一切正常。
当我得到我的收藏时
public function index()
{
$alarmables = Alarmable::orderByDesc('date')->take(2000)->get();
$alarms = Alarm::orderBy('name')->get();
$alarmables = $alarmables->unique(function ($aa) {
return $aa['alarm_id'].$aa['alarmable_type'].$aa['alarmable_id'];
});
$alarmables = $alarmables->sortBy('date');
return view('alarmables.index', [
'alarmables' => $alarmables,
'alarms' => $alarms
]);
}
我不能称其为可怕的关系
class Alarmable extends Model
{
public function alarm()
{
return $this->belongsTo('App\Alarm');
}
public function alarmable()
{
return $this->morphToMany('App\Alarmable', 'alarmable');
// return $this->morphedByMany('App\Alarmable', 'alarmable');
}
}
我的刀
<td>{{ $aa->alarmable ? $aa->alarmable->name : '' }}</td>
它给出了这个错误
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'alarmables' (SQL: select `alarmables`.*, `alarmables`.`alarmable_id` as `pivot_alarmable_id`, `alarmables`.`alarmable_type` as `pivot_alarmable_type` from `alarmables` inner join `alarmables` on `alarmables`.`id` = `alarmables`.`alarmable_id` where `alarmables`.`alarmable_id` = 2 and `alarmables`.`alarmable_type` = App\Alarmable) (View: D:\xampp\htdocs\apk\resources\views\alarmables\index.blade.php)
有没有简单的解决方法?我是否需要再使用一个模型,而不是只为所有的 Alarmable 模型?
【问题讨论】:
-
因为我不是 Laravel 人 - stackoverflow.com/questions/51551812/… 能解决这个问题吗?
-
我正在尝试使用那里的知识,但多态表有点复杂,所以到目前为止还没有运气。