0

i would like make a select from two tables, clients and loans. The query (In MySQL syntax) would be something like this:

SELECT * FROM loans, clients WHERE loans.status = 1 AND loans.client_id = clients.id;

This are my models:

class Client extends Eloquent {
    public function loans()
    {
        $this->hasMany('App\Loan');
    }
}

class Loan extends Eloquent {
    public function clients()
    {
        $this->belongsTo('App\Client');
    }
}

How it would be the function using the eloquent model?

3
  • If you have the relationship in loans to attach to the client it belongs to then why now get all the loans with status=1 and just use that object to pull the client info. $loans = Loans::where('status',1)->get(); then $loans->clients()->field Commented Feb 26, 2018 at 19:13
  • Okay, i get the part of bring all the loans ($loans = Loans::where('status',1_->get()) Commented Feb 26, 2018 at 19:18
  • But, how it would be this: $loans->clients()->field?? How it would be the syntax? Commented Feb 26, 2018 at 19:18

2 Answers 2

2

Use the with method to get the loans and clients in one query rather than a separate query for each client.

$loans = Loans::with('clients')->where('status', 1)->get();

See the docs on Eager Loading for more info.

This will get you a collection of Loans which each contains a collection of Clients. If you want to iterate all the loans and clients, you could use a nested loop:

foreach ($loans as $loan) {
    // show loan info
    foreach ($loans->clients as $client) {
        // show client info
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Here is what you want

Loans::with('clients')->get();

here is documentation of eager loading
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.