[英]laravel - saving new model to database
I'm trying to get to grips with the Laravel framework, and I'm a bit confused with the ORM system. 我正在尝试使用Laravel框架,而我对ORM系统有些困惑。
I have 3 database tables: 我有3个数据库表:
projects (projectID, projectName, etc...) 项目(projectID,projectName等)
tags (tagID, tag) 标签(tagID,标签)
project_tags (ID, projectID, tagID) project_tags(ID,projectID,tagID)
So for example there might be the following data in the db: 因此,例如,db中可能包含以下数据:
projects: 项目:
1 --- My Project 1-我的项目
tags: 标签:
1 --- PHP 1-PHP
2 --- MySQL 2-MySQL
3 --- Javascript 3-JavaScript
project_tags 项目标签
1 --- 1 --- 1 1-1-1
1 --- 1 --- 2 1-1-2
I have managed to get the project_tags to come through on the Project mode, by doing this: 通过执行以下操作,我设法使project_tags进入“项目”模式:
public function tags(){
return $this->hasMany('ProjectTag', 'projectID');
}
But i'm confused as to how I can insert records when creating a new project. 但是我对创建新项目时如何插入记录感到困惑。
This is how I'm creating the project: 这就是我创建项目的方式:
$project = new Project();
$project->projectName = $_POST['name'];
$project->projectShortName = str_replace(' ', '', strtolower($_POST['name']));
$project->projectDesc = $_POST['content'];
$project->projectImg = str_replace(' ', '', strtolower($_POST['name'])) . '.png';
$project->projectAddedDate = date('Y-m-d H:i');
$project->projectUrl = ($_POST['url'] != '') ? $_POST['url'] : null;
// TAGS SHOULD GO HERE SOMEHOW
$project->save();
I have the tagIDs in an array, I'm just not sure how I'm supposed to use them. 我有一个数组中的tagID,我只是不确定我应该如何使用它们。
Thanks. 谢谢。
Many to many should be defined using belongsToMany
, not hasMany
多对多应使用
belongsToMany
而不是hasMany
定义
Try 尝试
public function tags(){
return $this->belongsToMany('Tag', 'project_tags', 'projectID', 'tagID');
}
and 和
$user->tags()->attach($tags);
where $tags
is your array of IDs. 其中
$tags
是您的ID数组。
See http://laravel.com/docs/eloquent#relationships for the docs on many to many 有关多对多文档的信息,请参见http://laravel.com/docs/eloquent#relationships
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.