Laravel Model无需主键即可保存数据

jl.*_*jl. 16 php laravel laravel-4

我有2个模特:个人资料和学生.配置文件包含主键id.学生模型没有任何主键,但有一个外键,profile_id,它链接到profile.id. 我的学生控制器中有一个激活学生的功能,在调用时将状态设置为0到1.我正在尝试使用save()来更新值,但无法执行此操作,提示我这样的消息:

Column not found: 1054 Unknown column 'id' in 'where clause'
Run Code Online (Sandbox Code Playgroud)

可以请指教?非常感谢你.

学生型号:

class Student extends Eloquent {

    protected $primary_key = null;
    public $incrementing = false;

    protected $fillable = array('username', 'password', 'status', 'profile_id');

    public function profile() {
        return $this->belongsTo('Profile');
    }
}
Run Code Online (Sandbox Code Playgroud)

档案型号:

class Profile extends Eloquent {

    protected $fillable = array('firstname', 'lastname', 'email', 'phone');

    public function student()
    {
        return $this->hasOne('Student', 'profile_id', 'id');
    }
}
Run Code Online (Sandbox Code Playgroud)

StudentController:

public function activate($id) {
        $student = Student::where('profile_id', '=', $id)->first();
        $student->status = 1;
        $student->save();
        return Redirect::to('students');
}
Run Code Online (Sandbox Code Playgroud)

c-g*_*fin 33

您可能需要考虑添加id字段.对Laravel和包非常重要(特别是聚合)

但如果你必须......

学生型号:(骆驼案件primaryKey属性)

class Student extends Eloquent {

    protected $primaryKey = null;
    public $incrementing = false;


    protected $fillable = array('username', 'password', 'status', 'profile_id');

    public function profile() {
        return $this->belongsTo('Profile');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 确认,当直接使用 db 时,东西超级简单,在 Laravel 中超级复杂。Laravel 需要主键。没有它,整个框架就会愚蠢地崩溃,完全没用。所以,用主键设计你的数据库,或者使用其他框架,因为 Laravel 对你没用。 (2认同)

ivo*_*oto 5

我遇到了同样的问题,无法为此表使用主键字段。

由于 Eloquent 无法像这样更新表,我解决了它,只需决定以不同的方式更新行:

NameOfMyTable::where('entity_type', 1)->update(['last_import' => Carbon::now()]);
Run Code Online (Sandbox Code Playgroud)