【问题标题】:How to get a part of a belongsTo relationship in Laravel?如何在 Laravel 中获取 belongsTo 关系的一部分?
【发布时间】:2018-12-14 11:52:13
【问题描述】:

我有一个名为Log 的模型。它有一个名为hash_id 的外键,以及与App\HashbelongsTo 关系。

我知道我可以通过调用Log::with('hash') 来检索相应的哈希条目,如here 所述。我想做的是检索相应哈希列的特定行,而不是每一行。所以像Log::with('hash', ['only' => 'name'])。这是因为我通过 AJAX 发送数据,并且不想发送很多不必要的列。我该怎么做?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    你可以通过两种方式来做

    使用匿名函数

    Log::with(['hash' => function($query) { 
        return $query->select('id','text');
    }])->get();
    

    第二种方式

      Log::with('hash:id,text')->get();
    

    记住一件事您需要选择关系列,否则 它不会工作

    更多信息请阅读article

    【讨论】:

    • 它可以工作,但是当我将它与select 结合使用时会停止工作。我怎样才能达到Log::with('hash:id,text')->select('log')->first()?因为这会变成hash null。
    • @Mav 你还需要在父表中选择关系列,否则它会给你空数据..(我也在回答亲爱的)
    【解决方案2】:

    你必须用:写所有的列

    Log::with('hash:id,text')
    

    这将只返回 id 和文本。

    附注:需要选择外键,否则关系为空

    Here you can read more about it

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2019-02-15
      • 2018-08-06
      相关资源
      最近更新 更多