【问题标题】:Foreign Key not working in Laravel外键在 Laravel 中不起作用
【发布时间】:2018-10-24 03:47:30
【问题描述】:

我正在创建 cms 应用程序。

有两个表 - 用户和帖子。用户表有每个用户的 id。另一方面,Posts 表的用户 id 引用了用户表的 id。

但是,在保存帖子时,我收到Field 'user_id' doesn't have a default value 的错误消息。为什么是这样?请帮帮我。

帖子表:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('title');
            $table->longText('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

仪表板控制器

<?php

namespace App\Http\Controllers\Dashboard;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Post;

class DashboardController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('dashboard.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('dashboard.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->description = $request->description;
        $post->save();

        return redirect()->intended('dashboard');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

后模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
}

用户模型:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fname', 'lname', 'email', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function getRememberToken()
    {
        return $this->remember_token;
    }

    public function setRememberToken($value)
    {
        $this->remember_token = $value;
    }

    public function getRememberTokenName()
    {
        return 'remember_token';
    }
}

虽然我定义了一个外键“user_id”,但它不会自动从用户表中获取 id。我该如何解决这个问题?

【问题讨论】:

  • 该错误是因为您没有在Post模型的保存方法中指定user_id。此外,外键定义不会自动从用户表中获取id。您应该指定与帖子相关的用户,然后您可以访问相关用户。
  • 谢谢,@ab_ab!明白了!

标签: laravel


【解决方案1】:

您没有保存 user_id:

public function store(Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->description = $request->description;
        $post->user_id = Auth::id();
        $post->save();

        return redirect()->intended('dashboard');
    }

【讨论】:

  • 如果我删除外键约束怎么办?这段代码会起作用吗?
【解决方案2】:

首先你需要添加关系到Post.php:

public function user(){
    return $this->belongsTo(User::class);
}

User.php:

public function posts(){
    return $this->hasMany(Post::class);
}

DashboardController 在行动store

public function store(Request $request)
{
    $post = new Post();
    $post->title = $request->title;
    $post->description = $request->description;

    $user = Auth::user()->id;
    $user->post()->save($post);
    return redirect()->intended('dashboard');
}

【讨论】:

    猜你喜欢
    • 2014-09-13
    • 2021-02-08
    • 2015-08-26
    • 2021-04-21
    • 1970-01-01
    • 2023-04-03
    • 2018-01-02
    • 2012-06-05
    • 2016-04-13
    相关资源
    最近更新 更多