Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent and Trimming fields for use in relationships

So I've got a couple of models which I'm setting up for use with Laravels Eloquent ORM...

The tables these models refer to are populated by a third party program, which I do not have much ability to edit, so the following annoyance I have to find a work-around for.

The users tables have string IDs, example: 1234

Some other tables (action logs for example) have a string foreign user ids, example: "1234"

As you can probably see here, the other tables add a " onto the user IDs, and as such, I can't run it straight through a laravel relationship, as "1234" ~= 1234...

So I'm trying to find out if there is some way I can run the "1234" through a trim function or similar to remove the "s before it gets used in the eloquent relationship.

And yes, I know it's silly to add ", as mentioned, it's a third party program. I'm going to try to see if they can change that functionality, but in the case they cannot, I need to find a way to work around it.

Any help would be appreciated :)

Example of the relationship code:

public function useractions(){
    return $this->hasMany('\App\UserActions','userid');
}



public function user(){
    return $this->belongsTo('\App\User','userid');
}

This is a crosspost from: https://laracasts.com/discuss/channels/eloquent/eloquent-and-trimming-relation-fields

like image 791
Kieran Avatar asked Feb 24 '17 23:02

Kieran


People also ask

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is advantage of eloquent in Laravel?

Eloquent is an ORM, which means can automatically handle the relationships of your models for you. You can retrieve related models without writing complex queries. You can even retrieve database information without any kind of database knowledge at all.

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.


1 Answers

You can use Eloquent Raw expressions.

public function useractions(){
    return \App\UserActions::Where(DB::raw("TRIM(userid)"), $this->userid)->get();
}
like image 98
Dumindu Perera Avatar answered Oct 12 '22 08:10

Dumindu Perera