【问题标题】:How to return a model with his relations in Laravel?如何用他在 Laravel 中的关系返回一个模型?
【发布时间】:2019-09-04 07:12:33
【问题描述】:

我与数据透视表有一个多对多关系。在我的模型 DeckPlayCard 之间,我怎样才能将我的甲板和他的 Playcard 放在里面?

类似这样的:

id: 1,
...
play_cards: [
    {
        id: 1, ...
    },
    {
        id: 2, ...
    }
]

我尝试使用with() 函数,但它不起作用。

这是我的功能:

public function addToDeck(Request $request)
{
    $play_card = Auth::user()->playCards()->where('uid', $request->card_uid)->first();
    $deck = Auth::user()->decks()->where('token', $request->deck_token)->first();

    if (!$play_card || !$deck) {
        return ResponseService::respondWithErrors(
            400,
            $this->routes_messages[__FUNCTION__],
            ['Error Deck or Uid unknow.']
        );
    }

    if ($play_card->decks()->find($deck->id)) {
        return ResponseService::respondWithErrors(
            400,
            $this->routes_messages[__FUNCTION__],
            ['Card already in this deck.']
        );
    }

    $deck->playCards()->attach($play_card);
    $deck->save();

    return ResponseService::respondOK(
        200,
        $this->routes_messages[__FUNCTION__],
        $deck
    );
}

【问题讨论】:

  • 你能发布你收到的消息或者你面临的问题是什么?
  • 能否附上模特的代码?

标签: laravel eloquent many-to-many relationship


【解决方案1】:

在您显示的代码中,成功响应中的$deck 不会显示任何相关的游戏卡,因为您从未在牌组上加载过关系。您访问了关系查询以添加新的游戏卡,但您从未真正运行查询来获取套牌的游戏卡。

但是,使用with 加载初始游戏卡也对您没有多大帮助。您的回复将包含原始游戏卡,但不会包含您刚刚添加的新游戏卡。修改相关记录不会影响已经加载的记录。

在这种情况下,将新卡附加到牌组的相关卡后,您需要重新加载关系才能使卡显示在响应中。

// Add the card to the deck.
$deck->playCards()->attach($play_card);

// Load (or reload) the new set of related playcards. This will populate
// the $deck->playCards attribute so it will show up in your response.
$deck->load('playCards');

附带说明,没有理由保存$deck。你没有修改它上面的任何东西。如果您尝试更新甲板上的 updated_at 时间戳,那仍然无法正常工作,因为如果模型不脏,它实际上不会更新任何字段。但是,如果这是您的目标,您可以使用 touch() 方法 ($deck->touch())。

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 2020-11-15
    • 2017-11-23
    • 2020-11-06
    • 2019-11-27
    • 2015-04-18
    • 1970-01-01
    • 2014-11-06
    • 2018-09-25
    相关资源
    最近更新 更多