2014-01-10 48 views
0

我一直在我的模型中使用雄辩。我有以下两个表:如何使用外键解决一对一关系问题

Singlecard 
    ->id 
    ->card_id 

Card 
    ->id 
    ->card_id 

我Singlecard模式具有以下功能:

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> 

这是扭曲:属性代码工作正确。它从我定义的一对多关系中攫取了正确的属性。但它从卡片表中抓取了错误的信息。即使我定义了要匹配的密钥,它也会根据卡片表中的singlecard ID和card_id进行匹配。

我试过删除钥匙,并没有做任何事情。我甚至将这个函数全部删除,只是为了验证这是被调用的函数。我不确定有什么问题?

UPDATE:

我想通了,我做了两两件事。其中,我使用Cards表中的id作为与Singlecards相匹配的记录。我也改变了我的功能在Singlecards模型像这样:

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

这让我正确查询的关系。

+0

你为什么引用'card_id'而不是'id'? –

+0

Card_id是卡信息的唯一ID。这两个人相互配合。这有点令人困惑。在卡表中,id是行号,card_id是指卡的id。在singlecard中,id是卡的唯一ID,card_id与卡表中的card_id行相匹配。 –

回答

0

我需要更新我的模型如何相关,并更好地形成关系。我还需要改变模型,以便Singlecards属于卡片。我认为它应该是相反的。

卡片包含有关各种卡片和单卡片的所有信息是每个人的手/甲板上是什么。我认为这会让Singlecards成为家长,但这是一个错误。一旦我改变模型的功能是这样的:

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

然后它的工作。

相关问题