#Product -> Review -> User

6 messages · Page 1 of 1 (latest)

boreal osprey
#

So i have a product detail page and want to display every review (morphMany), each review has a relationship to User (hasOne). But when i try to get the user out of my review i get a simple number 1 and not the user object. How can i do this?

winter solstice
#

Mind telling what exactly you're doing? Sounds like you're just accessing a property and not a relation

boreal osprey
#

ofcourse, so here is my migration:

    public function up(): void
    {
        Schema::create('reviews', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->unsignedBigInteger('by');
            $table->foreign('by')->references('id')->on('users');
            $table->text('title');
            $table->text('body');
            $table->integer('rating');
            $table->morphs('for');
        });
    }

So i have this product, which links to reviews:

    public function reviews(): \Illuminate\Database\Eloquent\Relations\MorphMany
    {
        return $this->morphMany(Review::class, 'for');
    }

in this review i'm trying to get the user

    public function by(): \Illuminate\Database\Eloquent\Relations\HasOne {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

and that user has a name

    protected $fillable = [
        'name',
...

which i'm trying to access

winter solstice
#

So how are you accessing this data?

#

Also, you have a by column and a relation named exactly the same. Dunno if this is the cause of your issue, but this can cause issues, since using $thing->by would return the column, not the relation. Following Laravel's conventions here would help a lot, since a foreign key would be named user_id or even author_id, by_id etc. Then the column and relation are named differently.

boreal osprey