使用自定义键从Laravel中的一对多关系中获取数组
问题描述:
我现在正在学习Laravel,并且很难理解如何从属于另一个表上的记录的一个表中获取一组记录关键。使用自定义键从Laravel中的一对多关系中获取数组
我有两个表:
titles
-------------------
id | title_name | created_at | updated_at
posts
-------------------
id | titles_id | content
我的路线/ {} TITLE_NAME由read()方法对我PagesController.php
public function read($title){
$title_name = $title;
$title_id = Title::find($title)->id;
$posts = Title::find($title)->posts;
return view('pages/read')->with([
'title_name' => $title_name,
'title_id' => $title_id,
'posts' => $posts
]);
}
被控制但这似乎并不输出任何东西。我有我的模型的设置是这样的:
Title.php
class Title extends Model
{
// Table Name
protected $table = "titles";
// Primary Key
protected $primaryKey = "title";
// Timestamps
public $timestamps = "true";
// Custom primaryKey
public $incrementing = false;
//relationship
public function posts(){
return $this->hasMany('App\Post', 'titles_id')->orderBy('created_at', 'desc');
}
}
post.php中
class Post extends Model
{
// Table Name
protected $table = "posts";
// Primary Key
protected $primaryKey = "id";
// Timestamps
public $timestamps = "true";
//relationship
public function titles(){
return $this->belongsTo('App\Title');
}
}
我认为问题是,当我做题::发现($标题) - > post,laravel试图找到titles_id = title_name的帖子,因为我将title_name设置为primaryKey,但我需要它在标题表中寻找id列,而不是名称...
答
好吧,我会的给你一个例子,说明你做错了什么。
表:
titles
-------------------
id | title_name | created_at | updated_at
posts
-------------------
id | title_id | content
不titles_id
但title_id
,雄辩喜欢这个更多。
你的控制器:
public function read($titleName){
// The first function argument is the name of the title,
// not the title model.
// Also don't use snake_case in laravel(Except helpers) but camelCase.
// We are not going to use find, you might have set the name as
// primary key, but the id column still exists.
// firstOrFail() means get the first result, if there isn't, throw
// a model not found exception(404).
$title = Title::where('name', $titleName)->firstOrFail();
return view('pages/read')->with([
// You could just do 'title' => $title, and do the rest in the view.
'title_name' => $title->name,
'title_id' => $title->id,
'posts' => $title->posts
]);
}
名称型号:
class Title extends Model
{
// $table not needed, laravel knows this(Yes pure magic).
// No, we don't want name as primary key.
// Timestamps is true by default, so we don't need it.
public function posts(){
return $this->hasMany(\App\Post::class)->orderBy('created_at', 'desc');
}
}
Post模型:
class Post extends Model
{
// This function should be called title, not titles.
public function title(){
return $this->belongsTo(App\Title::class);
}
}
+0
Thanks for the in-深度响应,我会试试这个并报告回来! – MerrickC
您可以使用标题::在哪里( '身份证',$ yourIdWhichWant) - >岗位; – Th3
它不输出什么?你有白色屏幕还是帖子没有显示? –
谢谢Th3我会尽力而为,让你们知道它是怎么回事。 @Jan它只是不显示帖子 – MerrickC