我正在使用 Laravel 5.3 广告,因为hasMany
关系存档问题。
我有表员工和活动,其中包含一对多关系,即每个员工都会执行许多活动。
当我使用associate()
向员工添加活动时,它会向我发送错误消息:
BadMethodCallException in Builder.php line 2440:
Call to undefined method Illuminate\Database\Query\Builder::associate()
以下是数据库结构和代码:
数据库结构:
employee (1st table)
– employee_id
– employee_name
- created_at
- updated_at
activity (2nd table)
– activity_id
– activity_name
- created_at
- updated_at
employee_activity (pivot table)
– employee_activity_employee_id
– employee_activity_activity_id
模型类员工:
class Employee extends Model
{
protected $table = 'employee';
protected $primaryKey = 'employee_id';
public function activity() {
return $this->hasMany('App\Models\Activity', 'employee_activity', 'employee_activity_employee_id', 'employee_id');
}
}
模特课程活动:
class Activity extends Model
{
protected $table = 'activity';
protected $primaryKey = 'activity_id';
public function employee() {
return $this->belongsTo('App\Models\Employee', 'employee_activity', 'employee_activity_activity_id' ,'activity_id');
}
}
控制器:
public function EmployeeActivityAssociation()
{
$employee_id = Input::get('employee_id');
$activity_ids = Input::get('activity_id'); // This is an array of activities
$employee = Employee::find($employee_id);
if (!empty($employee)) {
//Adding activity under the employee
foreach ($activity_ids as $id) {
$activity = Activity::find($id);
$employee->activity()->associate($activity);
$employee->save();
}
return 'Activities asscoiated to employee';
}
else {
return 'Employee not found';
}
}
我的关系定义不正确吗?
答案 0 :(得分:2)
您的关系未正确定义。通过查看表结构,它应该是many-to-many
关系。
Model Class Employee:
public function activity() {
return $this->belongsToMany('App\Models\Activity', 'employee_activity', 'employee_activity_employee_id', 'employee_id');
}
模特课程活动:
public function employee() {
return $this->belongsToMany('App\Models\Employee', 'employee_activity', 'employee_activity_activity_id' ,'activity_id');
}
所以你的控制器应该是:
public function EmployeeActivityAssociation()
{
$employee_id = Input::get('employee_id');
$activity_ids = Input::get('activity_id'); // This is an array of activities
$employee = Employee::find($employee_id);
if (!empty($employee)) {
$employee->activity()->attach($activity_ids);
return 'Activities asscoiated to employee';
}
else {
return 'Employee not found';
}
}
如果您想坚持一对多关系,那么您必须将表格模式更改为:
删除表employee_activity
表并在活动表中添加列employee_id
,然后根据one-to-many定义关系。
答案 1 :(得分:0)
使用多对多方案,并在迁移时,将表 'employee_activity' 上的字段 'activity_id' 定义为 'unique':
$table->unsignedInteger('employe_id');
$table->unsignedInteger('activity_id')->unique();
通过这种方式,您可以在“employee_activity”表上只注册一个与一名员工相关联的活动,而一名员工可以与许多活动相关联。否则,将产生一个独特的错误。