【问题标题】:How can I solve issue with One to One relationship using foreign keys如何使用外键解决一对一关系的问题
【发布时间】:2014-01-28 19:36:12
【问题描述】:

我一直在我的模型中使用 eloquent。我有以下两个表:

Singlecard
  ->id
  ->card_id

Card
  ->id
  ->card_id

我的单卡模型有以下功能:

public function info()
{
    return $this->hasOne('Card', 'card_id', 'card_id');
}

我用它来获取卡片(我的测试中只有一张卡片)。

$cards = Singlecard::where('deck_id', '=', $deck)->get();

foreach ($cards as $card) 
{
    $cards_array[] = $card;
}

它得到了正确的卡并使用 var_dump 我验证了这一点。然而,问题来了:

<div class="row singlecard">
    <a class="" href="{{ $single->id }}">
        <div class="large-2 columns">
            <img src="{{ $single->info->card_image }}">
        </div>

        <div class="large-10 columns">

            <div class="row">
                <div class="large-12 columns">
                    <p>{{ $single->info->name }}</p>
                </div>
            </div>

            <div class="row">
                <div class="large-12 columns">
                @foreach ($single->attributes as $attribute)
                    <p>{{ $attribute->alias }}</p>
                @endforeach
                </div>
            </div>

        </div>
    </a>
</div>

这里是转折点:属性代码工作正常。它从我定义的一对多关系中获取了正确的属性。但它从 Cards 表中获取了错误的信息。尽管我定义了要匹配的键,但它是根据单卡的 ID 和 Cards 表中的 card_id 进行匹配的。

我试过移除钥匙,但没有任何效果。我什至一起删除了该函数,只是为了验证那是被调用的函数。不知道怎么回事?

更新:

我想通了,我做了两件事。一,我使用 Cards 表中的 id 作为记录来匹配 Singlecards。我还在 Singlecards 模型中更改了我的函数,如下所示:

public function info()
{
    return $this->belongsTo('Card', 'card_id');
}

这让我可以正确地查询关系。

【问题讨论】:

  • 为什么你指的是card_id而不是id
  • Card_id 是卡信息的唯一标识。这两人一拍即合。这有点令人困惑。在卡片表中,id 是行号,card_id 是卡片的 id。在单卡中,id 是卡的唯一 id,card_id 匹配卡表中的 card_id 行。

标签: laravel laravel-4 eloquent


【解决方案1】:

我需要更新我的模型的关联方式并更好地形成这种关系。我还需要更改模型,以便 Singlecards 属于 Cards。我认为它应该是相反的。

卡片包含有关各种卡片的所有信息,而单张卡片是每个人的手牌/套牌中的内容。我认为这会使 Singlecards 成为父母,但这是一个错误。一旦我将模型中的函数更改为这样:

public function info()
{
    return $this->belongsTo('Card', 'card_id');
}

然后它起作用了。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    相关资源
    最近更新 更多