gpt4 book ai didi

php - 如何使用 Laravel 通过外键检索所有记录

转载 作者:可可西里 更新时间:2023-11-01 07:05:16 26 4
gpt4 key购买 nike

我正在尝试使用 Laravel 显示与外键 ID 匹配的所有表记录。但是,我的查询没有将任何记录拉入 View 。

如何找到与传入函数的外键 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);
}

views/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 匹配的所有引号:

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 中获益,要获得所有属于特定用户的报价,你必须首先声明关系:

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');
}
}

然后您可以使用我们上面定义的关系简单地获得包含所有相关引用的所需角色:

QuoteController.php

public function index($id) {
$quotes = Persona::with('quotes')->find($id)->quotes;
return View::make('quotes.index')->with('quotes', $quotes);
}

关于php - 如何使用 Laravel 通过外键检索所有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25108536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com