我现在正在学习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列,而不是名称...
您可以使用标题::在哪里( '身份证',$ yourIdWhichWant) - >岗位; – Th3
它不输出什么?你有白色屏幕还是帖子没有显示? –
谢谢Th3我会尽力而为,让你们知道它是怎么回事。 @Jan它只是不显示帖子 – MerrickC