Laravel 基于外键获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32047679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel get data based on foreign key
提问by user3634184
So I have 2 tables, TABLE1 and TABLE2. They are linked throug Eloquent: TABLE1 has manyTABLE2's, and TABLE2 has oneTABLE 1.They are linked with foreign keys as such: in TABLE2 table1_id -> links to -> TABLE1 id.
所以我有 2 个表,TABLE1 和 TABLE2。它们通过 Eloquent 链接: TABLE1有许多TABLE2,而 TABLE2有一个TABLE 1。它们与外键链接如下: 在 TABLE2 table1_id -> 链接到 -> TABLE1 id。
How do I retrieve the entire table data or TABLE 2,+ replace table1_idwith a column of table1 (let's say by booktitle for example)?
如何检索整个表数据或表 2,+ 将table1_id替换为 table1 的列(例如按书名说)?
Sorry for the abstraction, but this is the best way I can explain it? :D
对不起,抽象,但这是我能解释它的最好方法吗?:D
采纳答案by jedrzej.kurylo
The easiest way is to make use of Eloquent's eager loading and fetch all records from table2and their corresponding record in table1.
最简单的方法是利用 Eloquent 的预先加载并从table2 中获取所有记录及其在table1 中的相应记录。
This will do the trick:
这将解决问题:
$results = Table2::with('table1')->get();
foreach ($results as $table2record) {
echo $table2record->id; //access table2 data
echo $table2record->table1->booktitle; //access table1 data
}
回答by Guillermo Lobos Parada
You need to make the relationship in the models , for example if you have a "Category" and this has many "Products" you need to put this code in your model
您需要在模型中建立关系,例如,如果您有一个“类别”并且有很多“产品”,则您需要将此代码放入模型中
public function products()
{
return $this->hasMany('App\Product', 'foreign_key_you_have');
}
and when you need to retrieve all products associated to that category in your view you need to call the function of model, for example
当您需要在视图中检索与该类别关联的所有产品时,您需要调用模型的函数,例如
@foreach($category->products as $cp) // with $category->products you call all products associated to your foreign_key
<h1>{{$cp->price}}</h1>
@endforeach