Laravel - 获取多个表的数据

时间:2018-02-26 19:09:18

标签: php laravel laravel-5 eloquent laravel-eloquent

我想从两个表,客户和贷款中选择一个。查询(在MySQL语法中)将是这样的:

a_root = '/home/A'
b_root = '/home/B'
a_paths = [os.path.join(a_root, f) for f in os.listdir(a_root)]
b_paths = [os.path.join(b_root, f) for f in os.listdir(b_root)]
for a_path, b_path in zip(a_paths, b_paths):
    with open(a_path) as a_file, open(b_path) as b_file:
        a_data = a_file.read()
        b_data = b_file.read()
    # do stuff with a and b

这是我的模特:

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

使用雄辩模型的功能怎么样?

2 个答案:

答案 0 :(得分:1)

使用with方法在一个查询中获取贷款和客户,而不是为每个客户提供单独的查询。

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

有关详细信息,请参阅Eager Loading上的文档。

这将为您提供一系列贷款,每个贷款都包含一组客户。如果要迭代所有贷款和客户,可以使用嵌套循环:

foreach ($loans as $loan) {
    // show loan info
    foreach ($loans->clients as $client) {
        // show client info
    }
}

答案 1 :(得分:1)

这是你想要的

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

这里是热切载入的文件 https://laravel.com/docs/5.5/eloquent-relationships#eager-loading