如何创建涉及两个没有相同属性的表的搜索功能?

时间:2017-07-19 05:42:26

标签: php laravel

我复制了http://justlaravel.com/search-functionality-laravel/来制作我的搜索功能。

web.php

<?php
use App\User;
use Illuminate\Support\Facades\Input;

Route::get ( '/', function () {
    return view ( 'welcome' );
} );

Route::any ( '/search', function () {
    $q = Input::get ( 'q' );
    $user = User::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'email', 'LIKE', '%' . $q . '%' )->get ();
    if (count ( $user ) > 0)
        return view ( 'welcome' )->withDetails ( $user )->withQuery ( $q );
    else
        return view ( 'welcome' )->withMessage ( 'No Details found. Try to search again !' );
} );

这是视图,其中显示结果

查看

<div class="container">
@if(isset($details))
    <p> The Search results for your query <b> {{ $query }} </b> are :</p>
<h2>Sample User details</h2>
<table class="table table-striped">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach($details as $user)
        <tr>
            <td>{{$user->name}}</td>
            <td>{{$user->email}}</td>
        </tr>
        @endforeach
    </tbody>
</table>
@endif
</div>

所以,例如,如果我有一个用户表,这里有一个名称和电子邮件列。在同一个数据库中我有一个Dogs Table,它有品种列和颜色列。

如果我希望搜索框在两个表上搜索并显示两个表的结果(如果它们都具有相同的值),我应该向此代码添加什么?非常感谢你。

1 个答案:

答案 0 :(得分:1)

Route::any ( '/search', function () {
$q = Input::get ( 'q' );
$results = array() ;
$user = User::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'email', 'LIKE', '%' . $q . '%' )->get ();
$dog = Dog::where ( 'breed', 'LIKE', '%' . $q . '%' )->orWhere ( 'color', 'LIKE', '%' . $q . '%' )->get ();
$results['dog'] = $dog ;
$results['user'] = $user ;
if (count ( $results['dog'] ) > 0 || count ( $results['user'] ) > 0 )
    return view ( 'welcome' )->withDetails ( $results )->withQuery ( $q );
else
    return view ( 'welcome' )->withMessage ( 'No Details found. Try to search again !' );
} );

并在正确的位置查看$ results ['dogs']和$ results ['user']

你也应该在控制器而不是路线

中完成所有这些