Laravel数据表搜索belongsToMany名称

时间:2017-07-14 07:30:26

标签: php laravel datatables

我试图通过belongsToMany关系中表格的name列搜索数据表。在这种情况下,表格为tags

以下是相关表格:

Schema::create('leads', function (Blueprint $table) {
    $table->increments('id');
    $table->text('data');
    $table->timestamps();
});

Schema::create('tags', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('color');
    $table->timestamps();
});

Schema::create('tag_lead', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('lead_id');
    $table->integer('tag_id');
});

这是我的型号代码:

class Lead extends \Eloquent
{
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}

这是我的控制器代码:

$leads = Lead::with('tags')->get();

return Datatables::of($leads)
    ->filterColumn('tags', function($query, $keyword) {
        $query->whereRaw('tags.name like ?', ['%'.$keyword.'%']);
    })
    ->make(true);

这是我的JS代码:

$('#leads-datatable').DataTable({
    ajax: '{{ route('backend.leads.datatable') }}',
    columns: [
        { data: 'id' },
        { data: 'data' },
        { data: 'tags', sortable: false },
        { data: 'created_at' },
        { data: 'updated_at' }

    ]
});

这不起作用并产生错误mb_strtolower() expects parameter 1 to be string, array given

我只想让数据表搜索每个潜在客户的所有标签名称。我该怎么做?

2 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,那么您正在寻找leadstag$keyword个变量的$leads = Lead::whereHas('tags', function($q) use($keyword) { $q->where('name', '=', $keyword); }) ->with('tags') ->get(); return $leads; 个人?如果是这种情况,您只需将Controller代码更改为:

Sub Main()

    Dim FileName As String = "test.a"
    Dim ListofName() As String = {"Name1", "Name2", "Name3", "Name4",
            "Name5", "Name6", "Name7", "Name8", "Name9", "Name10"}

    Try

        Dim FileNumber1 As Integer = FreeFile()
        FileOpen(FileNumber1, FileName, OpenMode.Random,
                 OpenAccess.ReadWrite, OpenShare.Shared, 600)

        FileGet(FileNumber1, People, 1)

        'Create File if needs be
        If People.Name = "" Then
            For A = 1 To 10
                People.Name = ListofName(A - 1)
                FilePut(FileNumber1, People, A)
            Next
        End If

        'Lock the recoard we want for testing
        Lock(FileNumber1, 9)

    Catch ex As Exception
        FileClose()
    End Try
    FileClose()
End Sub

答案 1 :(得分:0)

我最终只需将其从集合切换到查询:

    $leads = Lead::with('tags')
        ->select('leads.*')
        ->leftJoin('lead_tag', 'lead_tag.lead_id', '=', 'leads.id')
        ->leftJoin('tags', 'tags.id', '=', 'lead_tag.tag_id')
        ->groupBy('leads.id');

    $dt = Datatables::of($leads);