我有三张桌子和一张桌子。相应的型号:
表 ------ 型号
论文------论文paper_stocks ------ PaperStock
paper_stock_amounts ------ PaperStockAmount
纸张包含差异。纸张类型。 PaperStock包含可存放这些纸张的不同位置 PaperStockAmount包含纸张ID,库存ID和数量,以确定纸张B中有多少纸张。
现在我想检查一下纸上传出的每个库存中有多少。因此我在我看来这样做:
DELETE FROM TestTranslationTable WHERE ID IN(
SELECT Id FROM TestTranslationTable tblMain
WHERE tblMain.Id NOT IN (SELECT TOP 1 tblNested.id FROM TestTranslationTable tblNested WHERE
tblNested.TranslationConnectionId=tblMain.TranslationConnectionId ORDER BY tblNested.TranslationConnectionId)
AND tblMain.TranslationConnectionId IN(SELECT TranslationConnectionId FROM TestTranslationTable
GROUP BY TranslationConnectionId HAVING COUNT(TranslationConnectionId)>1 )
)
GO
这应该显示每种类型的纸张以及哪些库存以及它们的数量。
然而这是错误:
@foreach($papers as $paper)
@foreach($paper->paperStockAmount as $ps)
<tr>
<td>{{ $ps->stock->name }}</td>
<td>{{ $ps->amount }}</td>
</tr>
@endforeach
@endforeach
关系定义如下:
纸张
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'paper_stock_amounts' (SQL: select `paper_stock_amounts`.*, `paper_stock_amounts`.`id` as `pivot_id`, `paper_stock_amounts`.`amount` as `pivot_amount` from `paper_stock_amounts` inner join `paper_stock_amounts` on `paper_stock_amounts`.`id` = `paper_stock_amounts`.`id` where `paper_stock_amounts`.`id` in (1, 2))
PaperStockAmount
class Paper extends Model
{
public function paperStockAmount()
{
return $this->belongsToMany('App\PaperStockAmount', 'paper_stock_amounts')->withPivot('amount');
}
}
为什么这不起作用?
答案 0 :(得分:0)
您已定义paper
&amp;之间的M-M关系paper_stock
。
即。如果您从paperStockAmount
获取$paper
,那么您将获得paper_stock
个结果列amount
的结果。
你应该这样做:
@foreach($papers as $paper)
@foreach($paper->paperStockAmount as $paper_stock)
<tr>
<td>{{ $paper_stock->name }}</td>
<td>{{ $paper_stock->pivot->amount }}</td>
</tr>
@endforeach
@endforeach
使用pivot
获取名为 - amount
希望这有帮助!
答案 1 :(得分:0)
我不确定但看起来您Paper
到PaperStockAmount
的关系是has-many
,所以您的关系应该是:
纸张
class Paper extends Model
{
public function paperStockAmount()
{
return $this->belongsToMany('App\PaperStockAmount');
}
}
然后您的视图代码将起作用。
OR
如果Paper
和PaperStock
之间的关系为many-to-many
,则您的关系应为:
纸张
class Paper extends Model
{
public function paperStockAmount()
{
return $this->hasMany('App\PaperStock', 'paper_stock_amounts')->withPivot('amount');
}
}
然后在您看来,它可以被访问为:(从@saumya回答)
@foreach($papers as $paper)
@foreach($paper->paperStockAmount as $paper_stock)
<tr>
<td>{{ $paper_stock->name }}</td>
<td>{{ $paper_stock->pivot->amount }}</td>
</tr>
@endforeach
@endforeach