0

我希望我正确地描述了这个主题。我正在创建一个联系人管理应用程序,每个用户将在同一个联系人表中拥有自己的联系人。用户不得看到彼此的联系人。

我开始这样做,但必须有更好的方法:

$contact = Contact::where('user_id', Auth::user()->id)->find($id);

上面这行的问题是我想这样写:

$contact = Contact::find($id)

有没有办法像过滤器一样加载 where 子句,以便所有搜索都必须匹配Auth::user()->id

4

2 回答 2

0

如建议的那样,您可以使用查询范围。Contact在你的模型中添加这个:

public function scopeOfUser($query, $user_id)
{
    return $query->where('user_id', '=', $user_id);
}

然后像这样使用它:$contacts = Contact::ofUser(Auth::user()->id)->get();.

于 2014-06-06T09:50:30.620 回答
0

我在 laracasts.com 上找到了我正在寻找的答案。(视频:简化的存储库)

我通过创建存储库解决了这个问题。例如在我的 ContactController 中:

$contact = Contact::where('user_id', Auth::user()->id)->find($id);

就是现在

$contact = $this->contact->getAll();

DbRepository 文件具有:

public function getAll() {
    return $this->model->where('user_id', Auth::user()->id)->get();
}

它还有很多内容,您需要查看视频来进行设置。设置的工作量要多得多,但要干净得多,而且我的所有控制器都可以使用 DbRepository,因为每个表都有一个 user_id 字段。

于 2014-06-14T14:57:40.590 回答