【问题标题】:reciveing 2 records from a hasOne relation laravel 5.6从 hasOne 关系 laravel 5.6 接收 2 条记录
【发布时间】: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 模型上调用-&gt;get(),然后循环它们并打印$invoice-&gt;user-&gt;title;。我想你有两张发票,每张都有相同的用户。也许您应该尝试以不同的方式获取您的客户,例如$clients = User::has("invoices")-&gt;get();,它只会返回有发票的客户。

标签: php laravel


【解决方案1】:

问题是我正在循环遍历该模型可能发生的所有关系,所以我只做了一个简单的过滤器,它是我的关系的一个 are 子句,并设置发票的 id 以仅带来我的属性需要,而且效率更高,正如我在文档中看到的那样

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

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2018-05-29
    • 2017-04-21
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    相关资源
    最近更新 更多