私はlaravelの1対多関係について質問があります。1対多数の関係は機能していません
このページに基づいてプログラムを作成しようとしています。 https://manablog.org/laravel_bulletin_board/
私のプログラムはこちらです。
class PostsController extends Controller
{
public function index()
{
\DB::enableQueryLog();
$comments = Post::find(9)->comments;
$query = \DB::getQueryLog();
Log::debug($query);
$posts = Post::all();
$query = \DB::getQueryLog();
Log::debug($query);
return view('bbc.index')->with('posts', $posts);
}
}
class Post extends Model {
protected $table = 'posts';
protected $connection = 'mysql';
public function comments(){
return $this->hasMany('App\Comment','post_id', 'id');
}
}
class Comment extends Model{
protected $table = 'comments';
protected $connection = 'mysql';
public function post() {
return $this->belongsTo('App\Post');
}
}
テーブルはこちらです。
mysql> desc comments;
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| post_id | int(10) unsigned | NO | MUL | NULL | |
| name | varchar(50) | NO | | NULL | |
| content | varchar(300) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+------------+------------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
mysql> desc posts;
+------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+----------------+
| Id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| title | varchar(50) | NO | | NULL | |
| content | varchar(300) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+------------+------------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
私のプログラムは期待したとおりに動作しませんでした。 次にログを確認しました。 ログはこちらです。
[2017-08-31 18:25:47] local.DEBUG: array (
0 =>
array (
'query' => 'select * from `posts` where `posts`.`id` = ? limit 1',
'bindings' =>
array (
0 => 9,
),
'time' => 4.5099999999999998,
),
1 =>
array (
'query' => 'select * from `comments` where `comments`.`post_id` is null and `comments`.`post_id` is not null',
'bindings' =>
array (
),
'time' => 0.53000000000000003,
),
)
には関係ありません。 そしてなぜ私は理解できないのですか?comments
からcomments
を選択してください。 post_id
はnullで、comments
です。 post_id
はnullではありません。 この問題は何ですか?
Laravelのどのバージョンをお使いですか? –
このバージョンは5.4です。 –
あなたの '$ comments'クエリを理解しようとしています。あなたはそれを参照していないので、私はあなたがなぜそれを呼んでいるのか分かりません。 4秒の無駄のようです。 – mbozwood