Laravel get data based on foreign key

让人想犯罪 __ 提交于 2021-01-27 17:24:40

问题


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.

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)?

Sorry for the abstraction, but this is the best way I can explain it? :D


回答1:


The easiest way is to make use of Eloquent's eager loading and fetch all records from table2 and their corresponding record in 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
}



回答2:


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


来源:https://stackoverflow.com/questions/32047679/laravel-get-data-based-on-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!