【发布时间】:2018-12-01 22:40:39
【问题描述】:
这是我设置关系的模型
public function user() {
return $this->hasOne('App\Client','id','client_id');
}
这里是控制器 我在这里有两个关系,我的发票产品效果很好,但是 $clients 在视图中显示了 2 行
$clients = Invoice::with('user')->get();
$invoice_id = $invoice->id;
$invoices = Invoice::with('products')->where('id', '=', $invoice_id)->firstOrFail();
return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
和视图
@foreach($clients as $client)
<td>{{ $client->user->title ?? 'بدون مشتری' }}</td>
@endforeach
现在当我访问我的视图时,我得到 2 个具有相同客户端名称(标题)值的 td 标签,知道我做错了什么吗? 这是
的 dd#observables: []
#relations: array:1 [▼
"user" => Client {#769 ▼
#fillable: array:14 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:17 [▼
"id" => 1
"title" => "مشتری اول"
"description" => "مشتری اول"
"fax" => 123
"adrress1" => "مشتری اول"
"adrress2" => null
"adrress3" => null
"adrress4" => null
"adrress5" => null
"telephone1" => 123
"telephone2" => null
"telephone3" => null
"telephone4" => null
"telephone5" => null
"client_type" => null
"created_at" => null
"updated_at" => null
【问题讨论】:
-
对于所有发票,当您使用 get() 时,您将获得两个用户关系?
-
偶然有 2 个客户吗?
-
没有检查只有 1 个客户正在打印 2 次span>
-
改变关系 hasOne 到 belongsTo ( return $this->belongsTo('App\Client'); )
-
您在
Invoice模型上调用->get(),然后循环它们并打印$invoice->user->title;。我想你有两张发票,每张都有相同的用户。也许您应该尝试以不同的方式获取您的客户,例如$clients = User::has("invoices")->get();,它只会返回有发票的客户。