我现在正在学习Laravel,而且我很难知道如何根据一个键从一个表中获取属于另一个表中记录的记录数组。
我有两张桌子:
titles
-------------------
id | title_name | created_at | updated_at
posts
-------------------
id | titles_id | content
我的路由/ {title_name}由我的PagesController.php上的read()方法控制
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');
}
}
我认为问题在于,当我执行Title :: find($ title) - > post时,laravel正在尝试查找titles_id = title_name的帖子,因为我将title_name设置为primaryKey,但我需要它正在寻找标题表中的id列,而不是名称......
答案 0 :(得分:1)
好吧,我会举一个例子,说明你做错了。
表:
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');
}
}
发布模型:
class Post extends Model
{
// This function should be called title, not titles.
public function title(){
return $this->belongsTo(App\Title::class);
}
}