Quantcast
Channel: Yii Framework Forum
Viewing all articles
Browse latest Browse all 18717

Is There A Better Way To Do This (Model-User Relations)

$
0
0
Hello and thanks in advance for reading this topic. I am an experienced PHP dev but pretty new to Yii and MVC frameworks in general. I have gone through several tutorials and made a few small apps using Yii but am still discovering the best ways to do certain things. I really like how simple it is to associate models using the relations() method and then access that data but my question is regarding when I am inserting or loading data and how I verify it belongs to a certain user. Associating a user id with a record seems pretty straightforward, I just add an extra line to the actionCreate method generated by gii after the $model->attributes statement:

$model->attributes=$_POST['Model'];
$model->user_id = Yii::app()->user->id;


Is this the correct way to do it or is there a more accepted/standard way to make sure the user_id field of my models is populated with the user who created a record?

Secondly, when I'm using the view/update/delete actions I want to make sure they are only accessible by the user who created them. Gii auto-generates the function loadModel in the controllers which has no validation so I ended up adding a new function to the Controller.php class in the Components directory called loadModelByUser:

public function loadModelByUser($modelname,$id)
{
	$model = $modelname::model()->findByAttributes(array('id'=>$id,'user_id'=>Yii::app()->user->id));
	if($model===null)
		throw new CHttpException(404,'The requested page does not exist.');
	return $model;
}


Again, is there a better way to do this built into Yii which I missed in the tutorials?

Viewing all articles
Browse latest Browse all 18717

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>