请记住,Toyi 在我看来是最好的方法,我只是想让这对你来说尽可能简单,但他 100% 赞成 Eager Loading,因为它更有效。
所以您使用一对多关系,您的客户模型是父模型,但现在您制作 Invoice 模型 Inverse,所以第一件事是首先您必须确保每个 Invoice 都有一个整数“client_id”来存储每个每张发票上的客户 ID。我也只是为了安全起见,并确保它寻找正确的 id 设置你的模型。
客户端模型
public function invoices() {
return $this->hasMany('App\Invoice', 'client_id');
}
发票模型
public function clients() {
return $this->belongsTo('App\Client', 'client_id');
}
然后在您的控制器中,您将像这样提取该数据。
$client = Client::where('name','like', '%' . Input::get('name') . '%')->orWhere('lastname', 'like', '%' . Input::get('name') . '%')->get();
foreach($client->invoices as $invoice) {
echo $invoice->title; //Or What ever data you need to pull from your invoice.
}
请注意,我还添加了将输入添加到 orWhere 和 where 语句的方式。请记住,“%”有助于检查用户输入框中的意外 %。
预加载
更新这篇文章我看到你有以下代码:
$invoices = Facture::with('client')->where(function($q) {
$key = Input::get('client');
$q->where('nom', 'LIKE', '%'.$key.'%');
$q->orWhere('prenom', 'LIKE', '%'.$key.'%');
})->get();
我会做的是像这样传递输入,它可能会修复你的错误。
$key = Input::get('client');
$invoices = Facture::with('client')->where(function($q) or ($key) {
$q->where('nom', 'LIKE', '%'.$key.'%');
$q->orWhere('prenom', 'LIKE', '%'.$key.'%');
})->get();
这背后的原因是因为急切加载无法从外部放置字符串和变量,所以我通过将变量与函数一起传递并在 $invoices 之前将 $key 输入分配给它.如果这是有道理的。干杯希望这对你有用。