I'm trying to get to grips with the Laravel framework, and I'm a bit confused with the ORM system.
I have 3 database tables:
projects (projectID, projectName, etc...)
tags (tagID, tag)
project_tags (ID, projectID, tagID)
So for example there might be the following data in the db:
projects:
1 --- My Project
tags:
1 --- PHP
2 --- MySQL
3 --- Javascript
project_tags
1 --- 1 --- 1
1 --- 1 --- 2
I have managed to get the project_tags to come through on the Project mode, by doing this:
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.
Thanks.
Many to many should be defined using belongsToMany
, not 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.
See http://laravel.com/docs/eloquent#relationships for the docs on many to many
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.