Laravel Eloquent Relationship with 3 tables

259 views Asked by At

I need to get contact name using laravel Eloquent I have table stucture below :

CallLogs Table :

     id,user_id,PhoneNumber

Phone Table :

     id,PhoneNumber,contact_id

contact table :

     id,Name

//CallLogs Model :

public function phone()
{
    return $this->hasManyThrough('\App\Models\Phone','\App\Models\Contact','id','phoneNumber','phoneNumber');
}

// phone Model :

public function contact()
{
    return $this->belongsTo(Contact::class);
}

// Contact Model:

public function phones()
{
    return $this->belongsTo(Phone::class, 'contact_id');
}

Join Query : Please look with->(['phone']) in below query

$data = CallLogs::select('*')->where('call_type', '=', '1')
                 ->when($q, function ($query) use ($q) {
                     return $query->where(function ($query) use ($q) {
                         /** @var Builder $query */
                         $preparedQ = '%' . $q . '%';
                         $num = 0;
                         foreach (
                             [
                                 'to_call',
                                 'from_call',
                                 'callcost',
                                 'created_at'
                             ] AS $field
                         ) {
                             if ($num) {
                                 $query = $query->orWhere($field, 'LIKE', $preparedQ);
                             } else {
                                 $query = $query->where($field, 'LIKE', $preparedQ);
                             }
                             $num++;
                         }
                         return $query;
                     });
                 });

//dd($data);exit;
$outgoingcalls = $this->CallLogsFilter->applyFilter($request->get('filter', []), $data);

//$outgoingcalls = $data->paginate($count, ['*'], 'page', $pageNumber);

// Here I am using getting Name 

$outgoingcalls = $outgoingcalls->with(['phone'])
        ->sortable()
        ->paginate($count, ['*'], 'page', $pageNumber);
    $links = $outgoingcalls->appends(Input::except('page', 'table_only'))->links();
    $filter = $request->get('search');
    return compact('outgoingcalls', 'links','filter');
0

There are 0 answers