Laravel foreign keys not outputting expected results
P粉924915787
P粉924915787 2024-03-31 16:45:38
0
1
445

I'm developing a Laravel 9 web application with two tables (users and feedbacks) that use a foreign key named username Make a connection. A user can have a lot of feedback. As far as I know, if I get the user's details, the data also contains relevant feedback. My problem is that the user data is being fetched correctly but it comes with all the feedback instead of being connected to that specific user's feedback. Laravel executes such a query.

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

As I understand it, 0 should be replaced with the user's username. Is there something wrong here?

FeedbackModel-

class Feedback extends Model
{
    use HasFactory;

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

UserModel-

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_tableMigration-

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_tableMigration-

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');
        });
    }

FeedbackControllerGet data,

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

        dd($userData->feedbacks);

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

users Table-

feedback Table-

This is the output on the blade, as you can see it outputs all the feedback, even though I only requested nerigupex's feedback using routing.

If you need more code to solve this problem, please make a request and I will update the question accordingly. TIA.

P粉924915787
P粉924915787

reply all(1)
P粉378890106

Do this (only solves data loading issues)

1. Refactoring and migration

User migration

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

    .... rest of the code
}

Feedback Migration

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. Refactor model

//protected $primaryKey = 'username'; --> remove this

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

3. In feedback controller

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'));
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!