我正在尝试使用Laravel显示与外键id匹配的所有表记录。但是,我的查询没有将任何记录拉入视图。
如何找到与传递给函数的外键id匹配的所有记录?
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
模型/ Quote.php
class Quote extends Eloquent {
public $timestamps = false;
protected $table = 'quote';
protected $primaryKey = 'idquote';
}
模型/ Persona.php
class Persona extends Eloquent {
public $timestamps = false;
protected $table = 'persona';
protected $primaryKey = 'idPersona';
}
我有2个表,Persona和Quote,我试图拉出所有匹配外键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);
答案 0 :(得分:5)
如果您正在使用Eloquent,您必须获得其强大的ORM的好处,以获得所属的所有引用给特定用户,您必须首先声明关系:
<强>模型/ Persona.php 强>
class Persona extends Eloquent {
public $timestamps = false;
protected $table = 'persona';
protected $primaryKey = 'idPersona';
function quotes() {
return $this->hasMany('Quote', 'idquote');
}
}
<强>模型/ Quote.php 强>
class Quote extends Eloquent {
public $timestamps = false;
protected $table = 'quote';
protected $primaryKey = 'idquote';
function persona() {
return $this->belongsTo('Persona', 'idPersona');
}
}
然后,您可以使用我们上面提到的关系,通过所有相关引号简单地获得所需的persona
:
<强> QuoteController.php 强>
public function index($id) {
$quotes = Persona::with('quotes')->find($id)->quotes;
return View::make('quotes.index')->with('quotes', $quotes);
}
答案 1 :(得分:0)
使用Eloquent设置人物角色与报价模型之间的关系可能会有所帮助。
在您的情况下,您可能希望将“hasMany / belongsTo”关系应用为Quote-&gt; BelongsTo-&gt; Personas和Personas有很多引号?
http://laravel.com/docs/eloquent为您提供有关可能关系的更详细概述。