Php 使用'with'和'where'在Laravel中创建查询`

Php 使用'with'和'where'在Laravel中创建查询`,php,laravel,laravel-4,subquery,Php,Laravel,Laravel 4,Subquery,我想知道是否可以将where条件添加到with 例如: Comment::with('Users')->where('allowed', 'Y')->get(); 我试图找到一种更简单的方法来进行查询,避免使用看上去非常冗长的whereHas方法: $users = Comment::whereHas('users', function($q) { $q->where('allowed', 'Y'); })->get(); 我希望在内部生成的原始查询如下:

我想知道是否可以将
where
条件添加到
with

例如:

Comment::with('Users')->where('allowed', 'Y')->get();
我试图找到一种更简单的方法来进行查询,避免使用看上去非常冗长的
whereHas
方法:

$users = Comment::whereHas('users', function($q)
{
    $q->where('allowed', 'Y');

})->get();
我希望在内部生成的原始查询如下:

select * from comments, users
where users.id = comments.user_id and
users.allowed = 'Y'
我习惯于使用CakePHP,其中的查询看起来非常简单:

$this->Comments->find('all', array('Users.allowed' => 'Y'));
我定义的关系是:

//Comments.php
public function Users()
{
    return $this->belongsTo('Users');
}

//Users.php
public function Comments(){
    return $this->hasMany('Comments');
}
你可以试试这个

$users = User::with(array('comments' => function($q)
{
    $q->where('attachment', 1);

}))->get();
更新:或者,您可以在
用户
模型中的关系中使用where子句

// Relation for comments with attachment value 1
// and if hasMany relation is used
public function commentsWithAttachment()
{
    return $this->hasMany('Comment')->where('attachment', 1);
}

// Relation for all comments
// and if hasMany relation is used
public function comments()
{
    return $this->hasMany('Comment');
}
所以,你可以使用

// Comments with attachment value 1
User::with('commentsWithAttachment')->get();

// All comments
User::with('comments')->get();
更新:我认为您需要附件为1的用户的所有评论,如果这是您想要的,那么应该是评论而不是用户

Comment::with('user')->where('attachment', 1)->get();
在这种情况下,你的关系应该是

public function user()
{
    return $this->belongsTo('User'); // if model name is User
}

因为一条评论只属于一个用户。

这正是我所说的我想要避免的。很详细,对不起!我没弄明白,你能解释一下吗?我用
where has
发布了它,而不是
with
,但是对于这样一个简单而普通的操作来说,它看起来仍然非常大。现在它不起作用了,如果关系被定义为
belongsTo
,我想查询一个具有
hasMany
关系的连接表<代码>注释::with('Users')->其中('name','Paul')如何声明您的关系?