#Error while doing relationship existence query

1 messages · Page 1 of 1 (latest)

verbal pine
#

I don't know what I am doing wrong, I'd really appreciate some help. Thanks.

Migrations:

    public function up(): void
    {
        Schema::create('notes', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('content', 2000)->nullable();
            $table->smallInteger('x_coordinate')->nullable();
            $table->smallInteger('y_coordinate')->nullable();
            $table->smallInteger('width')->nullable();
            $table->smallInteger('height')->nullable();
            $table->foreignId('temporary_user_id')->nullable()->constrained();
        });
    }
    public function up(): void
    {
        Schema::create('temporary_users', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('ip');
        });
    }

Models:

class Note extends Model
{
    use HasFactory;

    protected $fillable = [
        'content',
        'x_coordinate',
        'y_coordinate',
        'width',
        'height',
    ];

    public function temporaryUser(): BelongsTo
    {
        return $this->belongsTo(Note::class);
    }
}
class TemporaryUser extends Model
{
    use HasFactory;

    protected $fillable = [
        'ip',
    ];

    public function notes(): HasMany
    {
        return $this->hasMany(Note::class);
    }
}

Query:

    public function index(Request $request): ResourceCollection
    {
        $ip = $request->ip();
        dd(Note::whereRelation('temporaryUser', 'ip', $ip)->get()); // <-- this one

    }

Error:

restive wren
#

Your Note model has an incorrect relationship to itself.

    public function temporaryUser(): BelongsTo
    {
        return $this->belongsTo(Note::class);
    }

Change it to the correct model and issue should be resolved