Laravel,如何在现有模型条件下调用或追加(加入)具有条件的另一个模型

时间:2015-08-07 14:52:14

标签: php laravel laravel-4

我遇到了来自两个不同表格(VenueHallVenue)的搜索功能。数据来自search1 parameter. I am able to search the data from one table ( VenueHall ) but I am not able to map with another table ( Venue ) using the existing object from the first table ( $ VenueHall`)。

$VenueHall = VenueHall::orderBy('created_at', 'DESC');
$VenueHall = $VenueHall->with('venue');
$VenueHall = $VenueHall->with('venueType');
$VenueHall = $VenueHall->with('venue.area');

if (Input::has('query') && $searchQuery = Input::get('query'))
{
    $perecentilify = '%'. $searchQuery .'%';

    $VenueHall = $VenueHall->where(function($query) use ($perecentilify, $searchQuery) {
        $query->where('name', 'LIKE', $perecentilify)
            ->orWhere('code', 'LIKE', $perecentilify);
            //->orWhere('from venue table');
        });                 
    }

    $data = array(
        'venueHall' => $VenueHall->paginate(2)
    );

    return View::make('venues/venues', array('data' => $data));

我无法映射来自//->orWhere('from venue table')表的Venue子句。请帮我根据搜索框中的搜索值从两个表中获取数据。

1 个答案:

答案 0 :(得分:0)

在这种情况下,我经常发现联接是最简单的解决方案:

$VenueHall = VenueHall
    ::join('Venue', 'Venue.id', '=', 'VenueHall.venue_id')
    ->where('VenueHall.name', 'LIKE', $perecentilify)
    ->orWhere('VenueHall.code', 'LIKE', $perecentilify)
    ->orWhere('Venue.name', 'LIKE', $perecentilify)
    ->orderBy('created_at', 'DESC')
    ->with(['venue', 'venueType', 'venue.area'])
    ->paginate(2)
;