Laravel根据外键获取数据 [英] Laravel get data based on foreign key
问题描述
所以我有2个表TABLE1和TABLE2.它们通过口才链接: TABLE1 有很多 TABLE2,而TABLE2 有一个 TABLE 1.它们通过以下方式与外键链接:在TABLE2 table1_id中->链接到-> TABLE1 id.
So I have 2 tables, TABLE1 and TABLE2. They are linked throug Eloquent: TABLE1 has many TABLE2's, and TABLE2 has one TABLE 1. They are linked with foreign keys as such: in TABLE2 table1_id -> links to -> TABLE1 id.
如何检索整个表数据或表2 ,并用table1列替换 table1_id (例如,以书名说)?
How do I retrieve the entire table data or TABLE 2, + replace table1_id with a column of table1 (let's say by booktitle for example)?
很抱歉抽象,但这是我能解释的最好方法吗?:D
Sorry for the abstraction, but this is the best way I can explain it? :D
推荐答案
最简单的方法是利用Eloquent的急切加载并从 table2 中获取所有记录以及它们在 table1中的对应记录.
The easiest way is to make use of Eloquent's eager loading and fetch all records from table2 and their corresponding record in table1.
这可以解决问题:
$results = Table2::with('table1')->get();
foreach ($results as $table2record) {
echo $table2record->id; //access table2 data
echo $table2record->table1->booktitle; //access table1 data
}
这篇关于Laravel根据外键获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!