首頁  >  問答  >  主體

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粉924915787225 天前447

全部回覆(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
  • 取消回覆