Laravel Eloquent与3张桌子的关系

时间:2017-08-31 11:08:32

标签: php laravel-5 laravel-eloquent laravel-query-builder

我需要使用laravel Eloquent获取联系人姓名 我有下面的表格结构:

CallLogs表:

     id,user_id,PhoneNumber

电话表:

     id,PhoneNumber,contact_id

联系表:

     id,Name

// CallLogs Model:

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

//手机型号:

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

//联系模式:

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

加入查询: 请在下面的查询中查看 - >(['phone'])

$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 个答案:

没有答案