php - Eloquent 渴望加载

标签 php laravel eloquent laravel-5

Eloquent 指南 http://laravel.com/docs/4.2/eloquent包含以下内容:-

Eager Load Constraints

Sometimes you may wish to eager load a relationship, but also specify a condition for the eager load. Here's an example:

$users = User::with(array('posts' => function($query)
{
    $query->where('title', 'like', '%first%');

}))->get();

In this example, we're eager loading the user's posts, but only if the post's title column contains the word "first".

如何扭转这一局面,以便只获得标题列包含“first”一词的帖子的用户?

换句话说,我只想要帖子包含“first”一词的用户,并且我想立即加载这些帖子。如果有 10 个用户,其中 3 个用户的帖子包含“first”一词,那么我的 get() 将仅返回 3 个用户,每个用户都有急切加载的帖子,且标题包含“first”。

最佳答案

我相信您正在寻找这样的东西(未经测试):

$first = 'first';
$users = User::whereHas('posts' => function($q) use ($first)
{
    $q->where('title', 'like', "%{$first}%");

})->with(['posts' => function($q) use ($first)
{
   $q->where('title', 'like', "%{$first}%");

}])->get();

关于php - Eloquent 渴望加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161820/

相关文章:

php - 使用 SimplePreAuthenticator 和 PreAuthenticatedToken 时处理临时 token 的最佳方法

java - PHP 开发人员关于 Java for Web Development 的问题

laravel - 语法错误,意外 'firstOrCreate' (T_STRING),期望变量 (T_VARIABLE) 或 '$

git - 带有包 git 工作流程的 Laravel 应用程序

php - 如何使用自定义社区/城市/州在 drupal 或 elgg 上注册?

php - Laravel - 根据表单结果更改查询依赖项

laravel-5 - 使用 Eloquent 获取具有一种或另一种角色的所有用户

mysql - 与 Laravel/Eloquent 的复杂关系

mysql - 如何在Laravel 5中处理BIT数据类型?

php - 检查时间戳是否为 x 小时?