更改laravel集合的基础

时间:2017-12-15 11:37:09

标签: laravel laravel-eloquent laravel-collection

是否有可能更改Laravel中docker.sock的“基础”?

要解释一下,如果我执行此操作:

get

我会得到这样的东西:

$books = App\Book::with('author')->get();
dd($books);

所以“基数”是Illuminate\Database\Eloquent\Collection {#903 all: [ App\Book {#932 id: 1, name: "book1", author: Illuminate\Database\Eloquent\Collection {#939 all: [ App\Author{#945 id: 1, name: "pippo" }, ], }, }, ], } ,我希望有Book的基数,如下所示:

Author

或者这个:

Illuminate\Database\Eloquent\Collection {#939
    all: [
        App\Author{#945
            id: 1,
            name: "pippo"
            },
        ],
    },

有可能以某种方式吗?



P.S。:在我的情况下,我不能改变get方法,所以第一部分

Illuminate\Database\Eloquent\Collection {#939
    all: [
        App\Author{#945
            id: 1,
            name: "pippo"
            book: Illuminate\Database\Eloquent\Collection {
                id: 1,
                name: "book1",
                },
            },
        ],
    },

无法更改

4 个答案:

答案 0 :(得分:0)

我猜你需要keyBy()雄辩的功能。示例:

$collection = collect([
        ['product_id' => 'prod-100', 'name' => 'Desk'],
        ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]);

    $keyed = $collection->keyBy('product_id');

    $keyed->all();

    /*
        [
            'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
            'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
        ]
    */

更多:https://laravel.com/docs/5.5/collections#method-keyby

答案 1 :(得分:0)

假设您有多个(书籍)到一个(作者)关系,您可以

$books = App\Book::with('author')->get();
$author = $books->first()->author

因为您要返回一个集合,您必须选择一个,即first(),然后获取作者。

此外:

$author = App\Book::with('author')->where('field', 'condition', 'value')->first()->author;

如果你想获得所有书籍:

$books = App\Book::with('author')->get();
$authors = [];
foreach($books as $book){
    $authors[] = $book->author;
}

答案 2 :(得分:0)

您可以转换该集合,并让它包含该书的作者。

$books = Book::with('author')->get();
$books->transform(function ($book) {
    return $book->author;
    }
);
dd($books);

这会迭代你的集合,并用提供的回调结果替换每个元素,在这种情况下是作者。

答案 3 :(得分:-1)

为什么不反过来:让所有拥有书籍的作者?

$authors = App\Author::whereHas('book')->get();