【问题标题】:Laravel 5.2 sending private message error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list'Laravel 5.2 发送私信错误 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list'
【发布时间】:2016-07-22 12:39:48
【问题描述】:

我收到此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list' (SQL: insert into `email` (`recipient_id`, `subject`, `message`, `user_id`, `updated_at`, `created_at`) values (0, asd, <p>dsa</p>, 1, 2016-04-02 19:17:55, 2016-04-02 19:17:55))

我的控制器:

public function mail(Request $request, Validator $validator)
{
    $validator = Validator::make($request->all(), [
        'usn' => 'exists:users',
        'send_subject' => 'required',
        'send_text' => 'required',
    ]);

    $user = User::all();
    $target = $request->usn;
    $check = $user->where('usn', $target)->first()['usn'];

    Auth::user()->email()->create([
        'recipient_id' => $check,
        'subject' => $request->send_subject,
        'message' => $request->send_text,
    ]);

    notify()->flash('Sucessfully send!', 'success');
    return redirect()->back();
}

用户.php:

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

电子邮件.php:

class Email extends Model
{
    protected $table = 'email';

    protected $fillable = [
        'sender_id',
        'recipient_id',
        'subject',
        'message',
    ];

    public function users() 
    {
        $this->belongsToMany('App\Users');
    }
}

电子邮件表:

Schema::create('email', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('sender_id')->unsigned();
    $table->integer('recipient_id')->unsigned();
    $table->string('subject');
    $table->text('message');
    $table->timestamps();


    $table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('recipient_id')->references('id')->on('users')->onDelete('cascade');
});

用户表:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->bigInteger('usn')->unique();
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->rememberToken();
    $table->timestamps();
});

【问题讨论】:

  • 您的email 表中没有user_id,而我可以看到sender_idrecipient_id

标签: mysql database laravel eloquent


【解决方案1】:

如果您不提供外键列名,Laravel 会对其进行假设。 https://laravel.com/docs/5.1/eloquent-relationships#one-to-many

// App\Email

public function users() 
{
    $this->belongsToMany('App\Users', 'sender_id');
}

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2019-06-26
    相关资源
    最近更新 更多