php - Any way to get all rows of a table where the foreign key matches the primary key using only models rather than accessing the database directly? -
I have two models: Users and Lessons Lessons Users_ID are linked to text for users in a lesson through foreign keys. I want to say "give me everything for user 8", but the only way I am able to accomplish this is db class
$ lessons = DB :: table ('lesson') - & Gt; Where ('user_id', '=', 8) - & gt; Find (); Is there any way to do something like this?
$ lessons = lesson :: all () - & gt; Where ('user_id', '=', 8); or (even better)
$ lessons = User :: find (8) -> lessons (); Just wondering because the latter two ways make more sense. just thinking!
You can do something like this:
$ Lessons = Lesson :: where ('user_id', 8) - & gt; get (); // '=' is optional or user with text: $ userWithLessons = User :: with (' Lesson ') - & gt; It seems (8); In addition to User :: Search (8) -> Lessons; will work, but curious loading (with '' ('lesson') ) is better. Another way: ID pass $ Id in // ID in the form of a user $ Lessons = lesson :: with ('user') - & gt; WhereHas ('user', use the function ($ q) ($ id) {$ q-> where ('id', $ id);}) - & gt; (Get); Update: You can try this ID $ id = 8; // user id $ lesson71 = with lesson :: ('user') - & gt; Where ('user', use the function ($ q) ($ id) {$ q-> where ('id', $ id);}) - & gt; Search (71);
Comments
Post a Comment