如何使用Laravel通过外键检索所有记录 [英] How to retrieve all records by foreign key with Laravel
问题描述
我正在尝试使用Laravel显示与外键ID匹配的所有表记录.但是,我的查询没有将任何记录拉入视图.
I am trying to display all table records that match a foreign key id using Laravel. However, my query is not pulling any records into the view.
如何找到与传递给函数的外键ID匹配的所有记录?
How do I find all of the records which match a foreign key id that is passed into the function?
routes.php:
Route::get('/personas/{idPersona}/quotes', 'QuoteController@index');
QuoteController.php:
public function index($id)
{
$quotes = Quote::where('idPersona', $id)->get();
return View::make('quotes.index')->with('quotes', $quotes);
}
视图/报价/index.blade.php:
<h2> Quotes </h2>
@foreach($quotes as $quote)
<li>{{ $quote }}</li>
@endforeach
models/Quote.php
class Quote extends Eloquent {
public $timestamps = false;
protected $table = 'quote';
protected $primaryKey = 'idquote';
}
models/Persona.php
class Persona extends Eloquent {
public $timestamps = false;
protected $table = 'persona';
protected $primaryKey = 'idPersona';
}
我有2个表,分别是Persona和Quote,并且我试图提取所有与外键idPersona匹配的引号:
I have 2 tables, Persona and Quote, and I am trying to pull all the quotes that match the foreign key idPersona:
CREATE TABLE `mountain`.`persona` (
`idPersona` INT NOT NULL AUTO_INCREMENT,
`fName` VARCHAR(45) NULL,
`lName` VARCHAR(45) NULL,
`mName` VARCHAR(45) NULL,
`bio` TEXT NULL,
`dateBorn` VARCHAR(45) NULL,
`dateDied` VARCHAR(45) NULL,
PRIMARY KEY (`idPersona`));
CREATE TABLE `mountain`.`quote` (
`idquote` INT NOT NULL AUTO_INCREMENT,
`quoteText` TEXT NOT NULL,
`quoteSource1` VARCHAR(100) NULL,
`quoteSource2` VARCHAR(100) NULL,
`tag1` VARCHAR(45) NULL,
`tag2` VARCHAR(45) NULL,
`tag3` VARCHAR(45) NULL,
`idPersona` INT NULL,
PRIMARY KEY (`idquote`),
INDEX `idPersona_idx` (`idPersona` ASC),
CONSTRAINT `idPersona`
FOREIGN KEY (`idPersona`)
REFERENCES `mountain`.`persona` (`idPersona`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
推荐答案
如果使用的是Eloquent,则必须获得其功能强大的ORM的好处,才能获取属于的特定用户的所有报价必须先声明关系:
If you are using Eloquent, you have to get benifit of its powerfull ORM, to get all quotes that belongs to specific user you have to declare the relations first:
models/Persona.php
class Persona extends Eloquent {
public $timestamps = false;
protected $table = 'persona';
protected $primaryKey = 'idPersona';
function quotes() {
return $this->hasMany('Quote', 'idquote');
}
}
models/Quote.php
class Quote extends Eloquent {
public $timestamps = false;
protected $table = 'quote';
protected $primaryKey = 'idquote';
function persona() {
return $this->belongsTo('Persona', 'idPersona');
}
}
然后,通过使用我们在上面定义的关系,您可以简单地得到具有所有相关引号的所需persona
:
Then you can simply get the desired persona
with all related quotes by using the relation we difined above:
QuoteController.php
public function index($id) {
$quotes = Persona::with('quotes')->find($id)->quotes;
return View::make('quotes.index')->with('quotes', $quotes);
}
这篇关于如何使用Laravel通过外键检索所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!