英文:
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('posts:title')-\>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('posts:title,user_id')->get();
答案2
得分: 1
$user = User::with(['posts' => function ($query) {
$query->select('title');
}])->get();
英文:
try this
$user = User::with(['posts' => function ($query) {
$query->select('title');
}])->get();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论