Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

I don't think you need both 'comments' and 'comments.users'.

$business = Business::find(1)->with(['comments.users'])->first();

This should give you both.

However, if you are going to allow users to comment on other things you may want to make the comments table polymorphic.

If you can only comment on business listings, you could also simplify this by treating the comments table as a pivot table with some extra data.

class Business extends \Eloquent {
    public function users()
        {
            return $this->belongsToMany('User', 'comments')->withPivot('comment')->withTimestamps();
        }
}

class User extends \Eloquent {
    public function businesses()
        {
            return $this->belongsToMany('Business', 'comments')->withPivot('comment')->withTimestamps();
        }
}

//To get all the user comments
$business = Business::find(1)->with(['users'])->first();

var_dump($business->toArray());

Last updated 1 year ago.
0

Thank you for your help.

I tried just using "comments.users" and it returned exactly the same array.

When I tried to set it up with your second suggestion it seemed further from what I wanted.

If you can picture a business listing page, with the business' details at the top of the page. Then a comments section that looks like:

Comments: Steve: This is a great company to work for. Bob: I agree. George: No it's not.

To me it seems that the comments are what should belong to the business and the comments should include the id and user's name from the users table. And the comment and created_at timestamp from the comments table.

My first description of what I was looking for may have been misleading. Hopefully this makes more sense.

Thank you again, Steve

Last updated 1 year ago.
0

The suggestion using the pivot table would still work to do what you describe.

$business->users->each(function($user){
    var_dump($user->name); //The user's name
    var_dump($user->pivot->comment) //The user's comment
    var_dump($user->pivot->created_at) //The time the user made the comment
}

You could also create your own join statement which I have been using most frequently for situations like this.

$comments = $business->where('businesses.id', $business_id)->join('comments', 'comments.business_id', '=', 'businesses.id')->join('users', 'users.id', '=', 'comments.user_id')->select('comments.comment', 'comments.created_at', 'users.name')->get();

var_dump($comments);
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

bangweb bangweb Joined 7 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.