timgws / QueryBuilderParser

A simple to use query builder for the jQuery QueryBuilder plugin for use with Laravel.
MIT License
159 stars 65 forks source link

Using with Eloquent, not just Laravel's QueryBuilder #49

Open lachlanhickey opened 3 years ago

lachlanhickey commented 3 years ago

Just wondering if collections are supported with this package? Or only DB:: queries?

timgws commented 3 years ago

@lachlanhickey, kind of.

It depends on what exactly you are trying to achieve, but you can usually do something along the lines of this:

    class Author extends \Illuminate\Database\Eloquent\Model {
        // ....
    }

    $author = new Author();
    // https://github.com/illuminate/database/blob/1e4476bac20b5c5e558efa02c4fb0ad46efd8013/Eloquent/Builder.php#L1353-L1361
    $table = $author->getQuery();
    $qbp = new QueryBuilderParser(
        // provide here a list of allowable rows from the query builder.
        // NOTE: if a row is listed here, you will be able to create limits on that row from QBP.
        array( 'name', 'email' )
    );

    $query = $qbp->parse($input['querybuilder'], $table);
Lirux commented 1 year ago

For future reference.

If someone wants to use the accessors or model relations of the result you could hydrate the results.

$table = DB::table('models')
// join the relation(s)
->leftJoin('relations', 'relations.id', '=', 'other_table.relation_id');
$qbp = new QueryBuilderParser(
        // provide here a list of allowable rows from the query builder.
        // NOTE: if a row is listed here, you will be able to create limits on that row from QBP.
        array( 'name', 'email' )
    );

$query = $qbp->parse($input['querybuilder'], $table);
$rows = $query->get();
$models = Model::hydrate($rows->all());

Then as usual

foreach($models as $model)
{
    echo $model->accessor;
    echo $model->relations->foo;
}