Ad

How To Use Eloquent Relationships With Yajra Datatables?

I am trying to use eloquent relationships to display the name of the patient instead of the patient id foreign key. Instead it only displays the patient id as if it doesn't see the relationship.

My controller function is:

   public function getActions(){
    $data = Action::all();
    return DataTables::of($data)
   ->addColumn('name',function(Action $action){
       return empty ($action->patient->first_name) ? $action->patient_id : $action->patient->first_name;
        //return DB::raw("SELECT * FROM 'patients' WHERE 'patients_id' = ?", $action->patient_id);
    })
    ->make(true);
} 

My js function in the view is:

    <script type="text/javascript">
        $(document).ready(function (){
          $('#actionTable').DataTable({
              processing: true,
              serverSide: true,
              ajax:'{!! route('get.actions')!!}',
              columns:[
                 {data:'action_id', name:'action_id'},
                 {data:'name', name:'name'},
                 {data:'action_status_id', name:'action_status_id'},
                 {data:'is_complete', name:'is_complete'},
              ]
          });
        })
     </script>

My Action class is:

    class Action extends Model
    {
        protected $table ="actions";

        protected $fillable=[
           'user_id', 'patient_id', 'option_id', 'action_status_id', 'is_complete', 'due_date',
        ];

        protected $primary_key = "action_id";

        public $incrementing = false;

        public function patients(){
              return $this->belongsTo('App\Patient','patient_id','action_id');
        }
   }

My Patients class is:

     class Patient extends Model
     {
        protected $table ="patients";

        protected $fillable=[
            'first_name', 'last_name', 'email', 'phone', 'dob', 'gender_id', 'is_active',
        ];

        protected $primary_key = 'patient_id';

        public $incrementing = false;

        public function actions(){
            return $this->hasMany('App\Action','action_id','patient_id');
        }
    }
Ad

Answer

The problem is that you have named your relation function inside your Action model as "patients". And you are calling

$action->patient->first_name.

I suggest renaming the relation function inside your Action Model to

public function patient()

It makes more sense.

Please refer to the documentation for more clarification One to One Relationships

Ad
source: stackoverflow.com
Ad