Php 拉维尔';s雄辩的ORM与查询生成器
我有两个表:Php 拉维尔';s雄辩的ORM与查询生成器,php,mysql,laravel,orm,eloquent,Php,Mysql,Laravel,Orm,Eloquent,我有两个表:用户和文章用户表中有一列名为已暂停,它接受是或否,而文章表中有一列名为已发布,它接受0或1。要从数据库中获取文章数据,articles.is_published必须等于1和用户。is_suspended必须等于no。现在假设users.is_suspended等于yes,如果我尝试使用以下查询生成器获取文章的数据: // first code: $articles = Article::join('users', 'articles.user_id', '=', 'user
用户
和文章
<代码>用户表中有一列名为已暂停
,它接受是
或否
,而文章
表中有一列名为已发布
,它接受0
或1
。要从数据库中获取文章数据,articles.is_published
必须等于1
和用户。is_suspended
必须等于no
。现在假设users.is_suspended
等于yes
,如果我尝试使用以下查询生成器获取文章的数据:
// first code:
$articles = Article::join('users', 'articles.user_id', '=', 'users.user_id')
->select(['articles.*', 'users.user_name', 'users.user_email'])
->where('articles.article_id', '=', 9)
->where('articles.is_published', '=', 1)
->where('users.is_suspended', '=', 'no')
->get();
// second code:
$articles = Article::with([
'user' => function($query) {
$query->select(['user_id', 'user_name', 'user_email'])
->where('users.is_suspended', '=', 'no');
}])
->where('articles.article_id', '=', 9)
->where('articles.is_published', '=', 1)
->get();
这将很好地工作,并且不会返回任何内容(因为users.is_suspended
=yes
)。现在,让我们尝试使用Laravel雄辩的ORM获取相同的文章,如下所示:
// first code:
$articles = Article::join('users', 'articles.user_id', '=', 'users.user_id')
->select(['articles.*', 'users.user_name', 'users.user_email'])
->where('articles.article_id', '=', 9)
->where('articles.is_published', '=', 1)
->where('users.is_suspended', '=', 'no')
->get();
// second code:
$articles = Article::with([
'user' => function($query) {
$query->select(['user_id', 'user_name', 'user_email'])
->where('users.is_suspended', '=', 'no');
}])
->where('articles.article_id', '=', 9)
->where('articles.is_published', '=', 1)
->get();
在这种情况下,我将得到下一个结果:
[
{
article_id: 9,
user_id: 1,
article_title: "Article title here",
article_body: "Article body here",
is_published: 1,
created_at: "2015-01-17 02:26:24",
updated_at: "2015-01-17 02:26:24",
user: null
}
]
即使用户被挂起,它也会获取文章的数据,这是错误的。所以我的问题是,如何修复第二个代码,使其像第一个代码一样工作 您可能希望将
与
一起使用,以确保延迟加载关系,但对其施加的任何约束仅适用于加载的关系。要将响应限制在用户未挂起的文章中,您需要使用该方法
你需要
whereHas
而不是with
(或者两者都需要,但在本例中不需要with
),就像@DavidBarker所说的那样
<>但是我建议更多,考虑这个代码的可读性:
$article = Article::whereHas('user', function ($q) {
$q->active();
})->published()->find(9);
它利用了
因此,以下是您可以做的事情,让您的生活更轻松:
被挂起
为bool
,因为:
$user->is_suspended; // no
(bool) $user->is_suspended; // true
用户
模型上定义范围暂停
,在文章
上定义范围发布
:
// Article model - on User accordingly
public function scopePublished($query)
{
$query->where('is_published', 1);
}
find($id)
或where('col',$id)->first()
而不是get
,因为后者将返回一个集合,即使只有一个结果那太好了。但是我如何选择特定的列以及应该放在哪里:select(['user\u id','user\u name','user\u email'])。我试着这样说:$q->select(['user\u id','user\u name','user\u email','created\u at'])->where('is\u suspended','=','no');但它导致的错误是:(基数冲突:1241个操作数应该包含4列)。为您添加它,您将它放在原来的位置,在
with
methods回调中。它导致的错误是:explode()希望参数2是字符串,对象给定。我的错误是,我没有将with参数包装在数组中。为了让它工作而改变。