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

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -