如何在与子模型相关的模型中仅获取所选列?

huangapple go评论48阅读模式
英文:

How to get only selected column in a child related model?

问题

以下是翻译好的内容:

我有两个模型,**`User`**  **`Post`**,其中一个 **`User`** 可以拥有多个 **`Post`** 模型。在我的应用程序中,我只想在查询 **`User`** 时检索相关的 **`Post`** 模型中的 **`title`** 列。这是我当前的代码:

```php
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

以下是我尝试的代码来检索相关的 Post 模型的 title 列:

$user = User::with('posts:title')->get();

然而,这会检索 Post 模型的所有列。我应该如何修改我的代码,只检索相关的 Post 模型的 title 列?谢谢!


<details>
<summary>英文:</summary>

I have two models, **`User`** and **`Post`**, where a **`User`** can have multiple **`Post`** models. In my application, I only want to retrieve the **`title`** column from the related **`Post`** model when querying for a **`User`**. Here is my current code:

class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}

class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}


Here is what I have tried to retrieve the **`title`** column for the related **`Post`** models:

    $user = User::with(&#39;posts:title&#39;)-\&gt;get();

However, this retrieves all the columns for the **`Post`** model. How can I modify my code to only retrieve the **`title`** column for the related **`Post`** models? Thank you!

</details>


# 答案1
**得分**: 2

如果你想获取选定列的数据,你还需要传递`FK`来确定它们之间的关系。

以下示例告诉你,帖子还需要`user_id`列来确定`POST`和`USER`模型之间的关系:

```php
$user = User::with('posts:title,user_id')->get();
英文:

If you want to get the data with selected column you also need to pass the FK to identify its relationship.

The example below tells the the post also need the user_id column to identify the relationship between POST and USER model

$user = User::with(&#39;posts:title,user_id&#39;)-&gt;get();

答案2

得分: 1

$user = User::with(['posts' => function ($query) {
$query->select('title');
}])->get();

英文:

try this

 $user = User::with([&#39;posts&#39; =&gt; function ($query) {
                      $query-&gt;select(&#39;title&#39;);
              }])-&gt;get();

huangapple
  • 本文由 发表于 2023年2月16日 11:08:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定