php - Laravel save nested model -
i using laravel 4 , got stuck problem.
i have 3 models: user, project, task.
relationships:
- user belongstomany('project')
- project belongstomany('user')
- project belongstomany('task')
- task belongsto('project')
i want store task no luck. following code maybe tells in more detail want accomplish:
auth::user()->projects($projectid)->tasks()->save($task);
with code get:
call undefined method illuminate\database\query\builder::tasks()
save task first.
then can try...
auth::user()->projects()->find($projectid)->tasks()->associate($task);
you may need modify project/task relationship. inverse of belongstomany
belongstomany
. thinking need hasmany
, belongsto
instead.
edit:
sorry think lead in wrong direction, got working.
$task = new task; $task->name = 'some super ultra task'; auth::user()->projects()->where('projects.id', $projectid)->first()->tasks()->save($task);
additionally, think made harder needed be.
$project = project::find($projectid); $project->tasks()->save($task);
that should work same. since know id of project looking for, shouldn't need go through user model first.
to check user owns project before saving, can add function project
model.
public function ownedbyuser($user_id) { if(user::find($user_id)->projects()->count()) { return true; } else { return false; } }
then use it, here did...
$project = project::find($projectid); if($project->ownedbyuser(auth::user()->id)) { $project->tasks()->save($task); } else { echo 'this isn\'t projec edit, fool!'; }
Comments
Post a Comment