framework icon indicating copy to clipboard operation
framework copied to clipboard

BelongsToThrough relationship needed

Open upngo opened this issue 12 years ago • 48 comments

Originally brought up and dismissed in #3052. (see for more examples)

The HasManyThrough relationship can not be used in both directions.

The simplest analogy is person a knows person b's phone number person b know's person c's phone number.

Person c can get person a's phone number via HasManyThrough.

Hasmanythrough does NOT work for getting from person a to person c as assumed (the reason #3052 was closed.

Related is #3786 where @taylorotwell commented "How can hasManyThrough NOT work both ways. If it works one way, it by definition must work the "other way". HasManyThrough cannot work this way because C does not point to B (foreign key), and B does not point to A (fk).

Currently two relationships are needed to represent this: A belongs to B B belongs to C.

upngo avatar Oct 20 '14 22:10 upngo

Since #3052 is closed, I will comment here. Hopefully everyone from that issue will notice this new one (cc @szainmehdi @Nirlah), even though they're not subscribed. It would be nice if Taylor would have a dialogue and understand issues before closing and ignoring them. But here's an explanation of how to achieve something similar to belongsToThrough that could have been given instead of "You would just use the same relationship both ways" (which is not true).

The caveat here is that it works slightly differently than hasManyThrough and the other native relationships. Those all create a single SQL query to get the related model. In this "solution", the intermediary model is loaded, so this will result in at least an additional query being executed. But it's all we've got until this is actually implemented.

Using the data models from https://github.com/laravel/framework/issues/3052#issuecomment-49672603, here is what the models should look like to make it work (if I'm understanding the expected relationships correctly... I'm trying to do something similar, and this setup works for me in the absence of a native belongsToThrough).

class Store extends Eloquent
{
    public function categories()
    {
        return $this->hasMany('Category');
    }

    public function items()
    {
        return $this->hasManyThrough('Item', 'Category');
    }
}

class Category extends Eloquent
{
    public function items()
    {
        return $this->hasMany('Item');
    }

    public function store()
    {
        return $this->belongsTo('Store');
    }
}

class Item extends Eloquent
{
    public function category()
    {
        return $this->belongsTo('Category');
    }

    public function store()
    {
        // Access belongsTo via Category. Inverse of hasManyThrough.
        if ($category = $this->category) {
            return $category->belongsTo('Store');
            // This also works (note the trailing parentheses):
            // return $category->store();
        } else {
            throw new DomainException('Store will only exist when a Category is assigned to an Item');
        }
    }
}

This may not work with overly complex queries, but it has proven successful for my basic needs.

jfexyz avatar Oct 23 '14 20:10 jfexyz

@joshuajabbour good response. The only think to watch out for with this workaround is that if Item does not have a category (and thus no store) it will result in an error (calling belongsTo or store() on a null object) instead of a null object as an ordinary relationship would.

upngo avatar Oct 23 '14 21:10 upngo

Yep, you're totally right. In my use case, the relationship is required, so I never ran into that. But it should def be checked for. Easy enough fix; updated the code...

jfexyz avatar Oct 23 '14 21:10 jfexyz

+1 on this, just ran into same issue

Also, the above check if category exists does not work. It instead results in an error: "Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation"

AngryUbuntuNerd avatar Nov 12 '14 16:11 AngryUbuntuNerd

+1

joeforshaw avatar Nov 17 '14 18:11 joeforshaw

+1

davidgittins avatar Dec 10 '14 14:12 davidgittins

+1

ssfinney avatar Dec 14 '14 22:12 ssfinney

+1

sleepless avatar Dec 20 '14 09:12 sleepless

+1

jenssegers avatar Dec 20 '14 09:12 jenssegers

+1

Just ran into the same issue. Ticket -> Ticket Type -> Event

Ticket has m:1 relationship with Event through Ticket Type, so a belongsToThrough() would make sense.

jbx1 avatar Dec 27 '14 17:12 jbx1

+1

crissi avatar Dec 29 '14 15:12 crissi

Ran into this issue today, +1 from me.

tpavlek avatar Jan 02 '15 19:01 tpavlek

+1

hotmeteor avatar Jan 03 '15 18:01 hotmeteor

+1

kalvisbuls avatar Jan 06 '15 11:01 kalvisbuls

+1

gmhenderson avatar Jan 07 '15 18:01 gmhenderson

+1

yaim avatar Jan 10 '15 13:01 yaim

Guys, if you find your self need access both ways, don't use hasManyThrough relation. You should know how your data need accessed. It's wrong if you design your table like this but you need access user from permission.

users:
    id
   name
roles:
   id
   name
   user_id
permissions:
   id
   role_id
   name

The solutions for them is create relations for each model. For example many to many, here the example:

user has many role
use has many permission
role has many user
role has many permission
permission has many role
permission has many user

The table for such as model structure is something like this

users:
   id
   name
roles:
  id
  name
roles_users
  id
  role_id
  user_id
permissions:
  id
  name
permissions_roles
  id
  role_id
  permission_id
permissions_users
  id
  user_id
  permission_id

After that setup you will get access both ways. From permission you can accesess related user and role, and is also possible from user to access related role and permission.

ghost avatar Jan 10 '15 19:01 ghost

@memtoko this is such an absurd post. While I appreciate that you're attempting to "solve" this - what you're proposing is not a solution. Designing databases that are properly normalized is not "wrong".

A user doesn't have permissions on a 1-to-1 in most cases, they have roles, and the roles assign the permissions. If I change the permissions for a role, all the users in that role should be affected. And I should not have to modify n rows of the table where n is the number of users. Because that's what you're suggesting, I'd have to change every row in the permissions_users table that was affected by the change, where if I model the data properly, as everyone in this thread is suggesting, I change a single row in role_permissions.

In short, this feature is simply missing. It doesn't mean the framework is horrible, it doesn't mean that Taylor doesn't understand databases, just simply the inverse of HasManyThrough has not been coded yet. And we would like it to be, at the earliest convenience.

tpavlek avatar Jan 10 '15 19:01 tpavlek

@tpavlek That's the problem of your request, You need access in not most case. Because you always need to solve "here a user, are this user has permission to doing this actions?" If you want users via permisssion, it's already available via roles property in permission if you define the structure of has many through relations. You don't need belongThrough, as you always access them via the intermedite relations.

Here the example taken from Laravel docs:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

It's make sense if you want to try to display posts in specifix country, so you define hasManyThrough relations. But if you need country when display a post, you already have it via property user. You don't need to define method country in a post, because that country is a data coming from the user.

ghost avatar Jan 10 '15 20:01 ghost

But if your models has connections many-to-many with another models through third models, and that is work in both ways as your request, then the tables may be something like this, you should add row a_id, b_id in intermediate table.

a
  id
  name
b
  id
  name
c
  id
  b_id
  c_id
  name
  etc

The real example coming from Rails, here their docs: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

ghost avatar Jan 10 '15 20:01 ghost