简体   繁体   中英

reciveing 2 records from a hasOne relation laravel 5.6

this is my model where i set my relation

public function user() {
    return $this->hasOne('App\Client','id','client_id');
}

and here the controller i have two relations here my invoice product realtion works fine and well but $clients shows 2 rows in view

$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'));

and the view

@foreach($clients as $client)
   <td>{{ $client->user->title ?? 'بدون مشتری' }}</td>
@endforeach

now when i visit my view i get 2 td tags with the same value of the client name (title) any idea what i have done wrong ? and here is the dd of the

#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

问题是我正在遍历该模型可能发生的所有关系,所以我只是做了一个简单的过滤器,该过滤器是我的关系的are子句,并设置了发票的ID以仅携带我需要的属性和那个如我在文档中所见,效率更高

        $clients = Invoice::with('user')->where('id','=',$invoice_id)->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM