0

是否可以更改getLaravel 中 a 的“基础”?

为了解释我,如果我执行这个:

$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"
            },
        ],
    },

或这个:

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

以某种方式可能吗?



PS:就我而言,我无法更改 get 方法,所以第一部分

$books = App\Book::with('author')

无法改变

4

4 回答 4

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

于 2017-12-15T11:45:23.240 回答
0

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

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

这将遍历您的集合并用提供的回调的结果替换每个元素,在这种情况下是作者。

于 2017-12-15T15:45:11.890 回答
0

假设你有一个多(书)对一个(作者)的关系,你可以做

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

因为您要返回一个集合,所以您必须选择一个 iefirst()并为此获取作者。

还:

$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;
}
于 2017-12-15T11:56:55.837 回答
-1

为什么不得到相反的结果:得到所有有书的作者?

$authors = App\Author::whereHas('book')->get();
于 2017-12-15T11:44:06.317 回答