我有一个关于laravel的一对多关系的问题。
我正在尝试根据此页面制作程序。 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
。comments
为空且post_id
。std::ifstream inFile(file, std::ios::binary);
if (!inFile.is_open() || !inFile.good()) {COUT "Error opening file\n"; return false; }
inFile >> script; // Here, it is skipping whitespaces, script is an std::string
不为空& #39;在这儿。
这是什么问题?
答案 0 :(得分:1)
我认为问题是因为您的ID列是Id
而不是id
。
MySQL本身不区分大小写,但PHP不是。
你可以:
将数据库中的Id
更改为id
(如果适用,还会迁移迁移文件)
或
将以下内容添加到您的模型中:
protected $primaryKey = 'Id';
并将您的关系更改为:
public function comments() {
return $this->hasMany('App\Comment');
}
//or
public function comments() {
return $this->hasMany('App\Comment', 'post_id', 'Id');
}
希望这有帮助!