如何使用 laravel 获取具有包含相同值的某些列的行

How to get rows that has certain columns containing same values using laravel

我有一个用户table,客户可以在其中自行注册或致电公司注册,以防过程对他们来说很复杂,我想组织客户列表以便:在一个页面中自己注册客户,在另一个页面中由员工注册客户,我的应用程序正在使用 Laravel/MySQL,但是查询太复杂了,我自己无法完成

这是我尝试使用 eloquent:

$clients = User::where([['role','Client'],['created_by','id']])->get();

此查询旨在 select 由同一个人创建的行,换句话说:如果我通过表单注册自己,我的行将如下所示:

id: 1
created_by:1 

但此查询无效。

我可以 select 所有行,并在我看来对每一行进行 if 测试,但这不是最佳选择,看起来像是作弊,我希望能够理解 [=24= 中的完美解决方案].为了发展自己的技能。

您可以使用 whereColumn,这在 laravels 文档的 Additional Where Clauses 部分中有描述。
对于 role 你使用正常的 where.

$clients = User::where('role', 'Client')->whereColumn('created_by', 'id')->get();

使用您的代码,您正在搜索 created_by 具有值 id 的用户。

试试这个

$clients = User::where(['role'=>'Client','created_by'=>'id'])->get();