问题
I'm trying to get all the "books" that one user have: but I can't do it how I need.
I use the following code:
/*Gets all books from the user whose id is 1*/
$books= User::find(1)->books();
That return to me an Collection
object; but I need a Builder
object, as I get when I use the "select" method.
/* This code return me a "Builder" object */
Books::select(array('id', 'name', 'type'));
I need the Builder
instead of Collection
because I using Bllim/Datatables on my project and this package just accept a Builder
object...
If I send it a Collection
its throw me the next error (500 - Internal Server Error):
{
"error":
{
"type":"ErrorException",
"message":"Undefined property: Illuminate\\Database\\Eloquent\\Builder::$columns",
"file":"\/var\/www\/proyect\/myproyect\/vendor\/bllim\/datatables\/src\/Bllim\/Datatables\/Datatables.php",
"line":256
}
}
Anybody knows the solution?
EDIT:
When I use the getQuery() method twice I get the following error:
{"error":{"type":"ErrorException","message":"array_values() expects parameter 1 to be array, null given","file":"\/var\/www\/proyect\/myproyect\/vendor\/bllim\/datatables\/src\/Bllim\/Datatables\/Datatables.php","line":550}}
Is rare, because when I used the "select" method Datatables worked perfectly...
This code works:
Books::select(array('id', 'name', 'type'));
But the code you told me doesn't work:
$user = User::find(1);
$user->books()->getQuery()->getQuery();
回答1:
Use method call books()
:
$user = User::find(1);
$user->books(); // relation object
$user->books; // dynamic property
First books()
returns a relation object, that you can chain Eloquenr\Builder
or Query Builder
methods on.
Second books
is a dynamic property - the query is automatically executed and its result is stored in the $user->relations['books']
and returned.
edit
As per comment - what you need is base Query\Builder
object if you want to access columns
property, so you need getQuery
twice:
$user->books()
->getQuery() // get underlying Eloquent\Builder
->getQuery() // get underlying Query\Builder
->columns // public property on the above
来源:https://stackoverflow.com/questions/27447389/how-to-get-a-builder-object-from-rows-related-to-pivot-laravel