首页  >  问答  >  正文

Laravel外键未输出预期结果

我正在开发一个 Laravel 9 Web 应用程序,其中有两个表(usersfeedbacks),它们使用名为 username 的外键进行连接。一个用户可以有很多反馈。据我所知,如果我获得用户的详细信息,这些数据也包含相关反馈。我的问题是,用户数据已正确获取,但它附带所有反馈,而不是连接到该特定用户的反馈。 Laravel 执行这样的查询。

select * from `feedback` where `feedback`.`username` = 0 and `feedback`.`username` is not null

据我了解,0 应该替换为用户的用户名。这里有什么问题吗?

反馈模型-

class Feedback extends Model
{
    use HasFactory;

    //One single user can have many feedbacks.
    public function user() {
        return $this->belongsTo(User::class);
    }
}

User模型-

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'username',
        'gender',
        'email',
        'password',
        'is_admin',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
        'is_admin',
    ];

    protected $primaryKey = 'username';

    public function feedbacks() {
        return $this->hasMany(Feedback::class, 'username');
    }

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

create_users_table迁移-

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('userId');
            $table->string('name');
            $table->string('username')->unique();
            $table->string('gender');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('is_admin')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
    }

create_feedback_table迁移-

public function up()
    {
        Schema::create('feedback', function (Blueprint $table) {
            $table->increments('feedbackId');
            $table->text('feedback');
            $table->string('username');
            $table->timestamps();
            $table->foreign('username')
                ->references('username')
                ->on('users')
                ->onDelete('cascade');
        });
    }

FeedbackController获取数据,

class FeedbackController extends Controller
{
    public function giveFeedback($username)
    {
        $userData = User::find($username);

        dd($userData->feedbacks);

        return view('feedback.givefeedback', compact('userData'));
    }
}

users 表-

feedback 表-

这是刀片上的输出,正如您所看到的,它输出了所有反馈,即使我只使用路由请求了 nerigupex 的反馈。

如果您需要更多代码来解决此问题,请提出请求,我将相应更新问题。 TIA。

P粉924915787P粉924915787175 天前376

全部回复(1)我来回复

  • P粉378890106

    P粉3788901062024-04-01 13:05:02

    这样做(仅解决数据加载问题)

    1。重构迁移

    用户迁移

    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id'); # change your current primary key to this
    
        .... rest of the code
    }

    反馈迁移

    Schema::create('feedback', function (Blueprint $table) {
        $table->bigIncrements('id'); # change your current primary key to this
        $table->unsignedBigInteger('user_id');
        $table->foreign('user_id')->references('id')->on('users');
    
        .... rest of the code
    }

    2。重构模型

    //protected $primaryKey = 'username'; --> remove this
    
    public function feedbacks() {
        return $this->hasMany(Feedback::class);
    }

    3。在反馈控制器中

    class FeedbackController extends Controller
    {
        public function giveFeedback($username)
        {
            $userData = User::with('feedbacks')->where('username', $username)->get();
    
            dd($userData->feedbacks);
    
            return view('feedback.givefeedback', compact('userData'));
        }
    }

    回复
    0
  • 取消回复