简体   繁体   English

Laravel 4:如何在where子句中使用Accessor

[英]Laravel 4: How to use an Accessor in a where-clause

Is it possible to use an Accessor for comparison in Laravel 4, for example: 是否可以在Laravel 4中使用Accessor进行比较,例如:

class User extends Eloquent {

   // define Accessor
   public function getSpecialNameAttribute()
   {
       return 'Joda';
   }

}

$User = User::where('gender','=','male')->where('specialName','=','Joda');

?

Yes, you can use it to filter query results: 是的,您可以使用它来过滤查询结果:

User
    ::where('gender','=','male')
    ->get()
    ->filter(function($item) {
        return $item->specialName === 'Luke';
    });

(!) Note that filtering will be applied after quering DB, so in case of big data this solution will have performance issues. (!)请注意,在查询数据库之后将应用过滤,因此在大数据的情况下,此解决方案将存在性能问题。

For more details I've googled for you this Collections tutorial . 有关详细信息,我已经用Google搜索了这个收藏教程

Also I suggest query scopes may be useful to complete your task in best way. 此外,我建议查询范围可能有助于以最佳方式完成您的任务。

No, you cannot use it this way. 不,你不能这样使用它。

When you use: 当你使用:

$user = User::where('gender','=','male')->where('specialName','=','Joda')->get();

you will try to compare specialName column in database with Joda string. 您将尝试将数据库中的specialName列与Joda字符串进行比较。

You cannot use accessor here, because accessor may be very complicated and then Laravel would need to take all data from table in database (for example 100000 records) and calculate accessors for all of them to get for you only records you need (for example 1 record). 你不能在这里使用访问器,因为访问器可能非常复杂,然后Laravel需要从数据库中的表中获取所有数据(例如100000条记录)并计算所有数据的访问器以获取所需的记录(例如1记录)。

You can use accessor only when you have object instance, and you won't be able to use it when querying database. 只有在具有对象实例时才能使用访问者,并且在查询数据库时将无法使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM