如何从与枢轴相关的行--Laravel获取一个Builder对象 [英] How to get a Builder object from rows related to pivot - Laravel

查看:134
本文介绍了如何从与枢轴相关的行--Laravel获取一个Builder对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个用户拥有的所有书籍:但是我无法做到这一点。

I'm trying to get all the "books" that one user have: but I can't do it how I need.

我使用以下代码:

/*Gets all books from the user whose id is 1*/     
$books= User::find(1)->books();

返回给我一个集合但我需要一个 Builder 对象,当我使用select方法时,我需要。

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'));

我需要 Builder 而不是 Collection 因为我在我的项目中使用Bllim / Datatables,而这个包只是接受一个 Builder 对象...

I need the Builder instead of Collection because I using Bllim/Datatables on my project and this package just accept a Builder object...

如果我发送一个集合,它会抛出下一个错误(500 - 内部服务器错误):

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?

编辑:

当我使用getQuery()以下错误:

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}}

是罕见的,因为当我使用选择方法Datatables工作完美...

Is rare, because when I used the "select" method Datatables worked perfectly...

此代码工作原理:

Books::select(array('id', 'name', 'type'));

但是你告诉我的代码不起作用:

But the code you told me doesn't work:

$user = User::find(1);
$user->books()->getQuery()->getQuery();


推荐答案

使用方法调用

$user = User::find(1);

$user->books(); // relation object
$user->books; // dynamic property

首先 books()返回一个关系对象,您可以链接 Eloquenr\Builder 查询构建器方法。

First books() returns a relation object, that you can chain Eloquenr\Builder or Query Builder methods on.

第二个书籍是一个动态属性 - 查询自动执行,其结果存储在$ code $ $ - >关系['books'] 并返回。

Second books is a dynamic property - the query is automatically executed and its result is stored in the $user->relations['books'] and returned.

编辑

根据评论 - 您需要的是基础 Query\Builder 对象,如果您要访问属性,所以你需要 getQuery 两次:

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

这篇关于如何从与枢轴相关的行--Laravel获取一个Builder对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆