我希望我正确地描述了这个主题。我正在创建一个联系人管理应用程序,其中每个用户将在同一联系人表中拥有自己的联系人。用户不能看到对方的联系人。
我一开始就是这么做的,但一定有更好的方法:
$contact = Contact::where('user_id', Auth::user()->id)->find($id);
上面这行的问题是我想这样写:
$contact = Contact::find($id)
有没有办法让where子句像过滤器一样加载,这样所有的搜索都必须匹配Auth::user()->id
?
按照建议,可以使用查询范围。将此添加到您的Contact
模型中:
public function scopeOfUser($query, $user_id)
{
return $query->where('user_id', '=', $user_id);
}
然后这样使用:$contacts = Contact::ofUser(Auth::user()->id)->get();
.
我在laracasts.com上找到了我一直在寻找的答案。(视频:repository Simplified)
我通过创建存储库解决了这个问题。例如在我的ContactController中:$contact = Contact::where('user_id', Auth::user()->id)->find($id);
现在$contact = $this->contact->getAll();
dbrerepository文件有:
public function getAll() {
return $this->model->where('user_id', Auth::user()->id)->get();
}
还有很多,你需要查看视频来设置它。这需要更多的工作来设置,但它更干净,dbrerepository可以被我所有的控制器使用,因为每个表都有一个user_id字段。