Home > Software engineering >  Eloquent retrieve data from another model on runtime
Eloquent retrieve data from another model on runtime

Time:03-17

I have two tables;

Data

  • id
  • name

Custom_data

  • id
  • data_id (references id on Data)
  • customer_id (references id on Customers)
  • name

When I retrieve all items from the database (via for example Data::all()) as Customer X then I want to retrieve values from 'Custom_data' in favor of the data in table 'Data' where the customer_id matches X

Example: Data contains name 'John Doe' with id 1

Custom_data contains a record with data_id 1 and name 'Jane Doe' and customer_id X

When retrieving the models I want to see Jane Doe instead of John Doe. Can this be done on a Model level in Eloquent? This is just a simple example, in our application we have multiple columns that need to be retrieved (firstname, lastname, street, etc. etc.)

How I am currently retrieving the fields is like this:

public function getNameAttribute($name) {

$customData = CustomData::where('customer_id', $this->customer_id)->where('data_id', $this->id)->first();
if(null != $customData) {
  return $customData->name;
 } else {
  return $name;
 }
}```

CodePudding user response:

Here' how you can do it:

In your Data.php modal file you need to add relationship:

public function CustomData(){
    return $this->hasOne(CustomData::class);
}

Now, you can use CustomData function on eloquent record anywhere in Controller or View at runtime to get related data.

Another approach is to get data on condition basis:

$users = User::select('users.id', 'users.username', 'users.active', 'users.parent_id', 'parent.username as parent_username')
            ->selectRaw("CASE WHEN GROUP_CONCAT(roles.name) = 'student' THEN user_profiles.secondary_email ELSE users.email END as email");

I've used this type of solution for another purpose where I needed to use email on condition basis.

CodePudding user response:

first you need to define relation in model

class DataModel extends Model{
    ...
    public function customData()
    {
        return $this->hasMany(CustomDataModel::class,"data_id");
    }
}

now you have access to this data.

$data = DataModel::with("customData")->first();
$data->name; // John Doe
$data->customData->name; // Jane Doe
  • Related