使laravel使用自定义列前缀

时间:2016-10-19 07:13:23

标签: php mysql laravel laravel-5 laravel-5.2

我有一个名为people_id而不是user_id的列,因此当我在laravel中运行查询时会抛出此错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list' (SQL: insert into `questions` (`user_id`, `created_at`) values (2, 2016-10-19 07:07:33))

如果表名为'people',我怎样才能使用people_id而不是user_id

我的App / User.php文件

<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    protected $table='people';
    protected $fillable = [
        'name', 'email', 'password','age'
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
    public function questions() {
        return $this->hasMany('App\questions');
    }
}

3 个答案:

答案 0 :(得分:1)

问题模型:

return $this->belongsTo('App\User', 'people_id');

https://laravel.com/docs/5.3/eloquent-relationships

答案 1 :(得分:0)

// Fallback button title.
// @discussion Allows fallback button title customization. A default title "Enter Password" is used when
//             this property is left nil. If set to empty string, the button will be hidden.
@property (nonatomic, nullable, copy) NSString *localizedFallbackTitle;

// Cancel button title.
// @discussion Allows cancel button title customization. A default title "Cancel" is used when
//             this property is left nil or is set to empty string.
@property (nonatomic, nullable, copy) NSString *localizedCancelTitle NS_AVAILABLE(10_12, 10_0);

答案 2 :(得分:0)

Eloquent根据模型名称确定关系的外键。在您的情况下,自动假定问题模型具有user_id外键。

所以,你应该改为

return $this->hasMany('App\questions', 'people_id');

也许您应该阅读:https://laravel.com/docs/5.2/eloquent-relationships