Laravel外键关系 - 字段列表中的未知列

时间:2016-04-05 09:26:33

标签: php laravel-5.2

我有会员和SkyMedRep模型:

class SkyMedRep extends Model
{
    protected $fillable = [
        'id','rep_id',
    ];

    public function members()
    {
      return $this->hasMany('App\Member');
    }
}

class Member extends User
{
    public function sky_med_rep()
    {
        return $this->belongsTo('App\SkyMedRep');
    }
}

这是会员的迁移:

public function up()
    {
        Schema::create('members', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('sky_med_rep_id')->unsigned();
        $table->timestamps();
    });

    Schema::table('members', function($table) {
       $table->foreign('sky_med_rep_id')->references('id')-   >on('sky_med_reps')->nullable(true);
    });
}

成员模型包含引用SkyMedRep模型的外键。在定义了这种关系后,我试图将SkyMedRep模型的对象分配给成员模型的对象,如:

$member->sky_med_rep = $sky_med_rep;

这里,$ member是Member模型的对象,$ sky_med_rep是SkyMedRep模型的对象。

当我尝试$ member-> save()时,我收到错误“字段列表中的未知列'sky_med_rep'”。似乎sky_med_rep无法作为外键引用处理。下面是我保存数据的代码:

    $member = new Member();
    $member->sky_med_member_number = $request->input("sky_med_member")['member_number'];
    $sky_med_rep = SkyMedRep::firstOrNew(['rep_id' => $request->input("sky_med_member")['rep_id']]);
    $sky_med_rep->name = $request->input("sky_med_member")['name'];
    $sky_med_rep->save();
    $member->sky_med_rep = $sky_med_rep;
    $member->save();

1 个答案:

答案 0 :(得分:1)

而不是$member->sky_med_rep = $sky_med_rep;你应该写$member->sky_med_rep->associate($sky_med_rep);

另请参阅http://www.php-fig.org/psr/psr-2/编码样式指南。方法名称应为camelCase,而不是下划线。