Kohana 3.2 reuse model to insert data - php

I'm currently working on a project that uses Kohana 3.2.
I haven't used the framework so I'm kind of a "beginner" though I've been using Symfony2 for quite some time.
Let's say I have a "task". This "task" can be assigned to multiple "users" at the same time.
This is achieved by entering the same "task" with different user_id. So I thought it shouldn't be a problem to reuse the model by simply to change the column's data and then calling $task->create().
For some reason this isn't working right and the code returns:
Kohana_Exception [ 0 ]: Cannot create task model because it is already loaded.
My current code is:
Model:
class Model_Task extends ORM{
protected $_table_name = 'task';
protected $_primary_key = 'task_id';
}
Code:
$task = ORM::factory('task');
$task->task = "some random task you need to finish.";
foreach($users as $user){
$task->user_id=$user;
$task->create();
}
Am I doing something wrong or you simply can't reuse models in Kohana?

You are using the same task object for all users, thus after first iteration task will be loaded after calling create method. Change your code to:
foreach($users as $user)
{
$task = ORM::factory('task');
$task->user_id = $user;
$task->create();
}

Related

Specific question Laravel Database Homepage

I started using Laravel few days before.
I'm actually struggling with a problem, I created a homepage and I want to replace some text of the page with content from my database.
So how do I create a model/controller, and after that I will make an admin panel, so I can edit them.
The only tutorials/docs I see are for making a form/post to create users
Example
In basic php it's easy you just do a pdo connection and then a fetch and you use your date as you want. How do you do it in laravel ?
To fetch data from the DB in Laravel can be done in 1 of two ways, 1. using a Model (the best way) or using a Query Builder, which is much more familiar to those migrating from pure PHP.
Using a Model
Create a model using php artisan make:Model (change Model with a name of your choosing) then open the model once created (found in app/Http/Models) and add the following under use HasFactory;:
protected $table = 'your_table_name';
protected $primaryKey = 'id'; // This is the column you usually set to PRIMARY
public $timestamps = true;
protected $fillable = [
'table_column',
'table_column',
];
To use the Model, import it into your Controller file like so use App\Models\Model; and then use it as so:
$flights = Flight::where('destination', 'Paris')->get();
Learn more about Models in Laravel here.
Using a Query Builder, not best practice
Import the DB facade in the controller like so use DB; then call upon it like so:
$db = DB::table('users')->where('name', 'John')->first();
Learn more about the Query Builder here.
I hope this helps, if not let me know how I can assist further.

Laravel get school users

I am making a project that will have schools that are already seeded into the database, one user has one school.
User table has school_id
I made this relationship:
User.php
public function school(){
return $this->belongsTo('App\Models\School');
}
School.php
public function user()
{
return $this->hasMany('App\Models\User', 'school_id');
}
When i do
$school = School::where('id', 1)->first();
dd($school);
I get every field from the school model but the users aren't there,how do i make that the users appear there too without having to do?
dd($school->user)
You should use the Eloquent feature called Eager Loading
So, to eager load all the users, you should do:
School::with('user')->get();
Alternatively, if you are willing to automatically load the user without having to specify with(‘user’) every time, you can set the $with property in your School model like this:
protected $with = [‘user’];
Nvm I fixed it by doing this query
$schools = School::with('user')->get();

Laravel : Search with posted parameters

I am new to Laravel so please be patient with me.
i have to implement search functionality in Laravel. i am able to send form data to the search controller and receiving it as well
public function search_results(Request $request){
if ($request->has('gender')) {
echo $request->gender;
}
.....
}
Now when i am following tutorials on the web i am getting such examples :
public function filter(Request $request, User $user)
{
// Search for a user based on their name.
if ($request->has('name')) {
$user->where('name', $request->input('name'))->get();
}
}
or
public function index()
{
$users = User::where('status', 1)
->where('is_banned', 0)
->get(['name']);
dd($users);
}
now i am not sure from where this User:: or User $user is being added, and what should i do in my scenario.
Your suggestions would be helpful ..
Thanks
The $user represents an object belonging to the model(User::) associated with a table(users) in the mvc structure. If you want to "Search for a user based on their name." That means you already have a users table in database , and a User model .
You can use eloquent queries to retrieve data from database.
A User.php file should be generated when you create a new laravel project with composer. You can check for that.
So when you declare a variable like this :
$user = User::first();
You are actually getting the first element in 'users' table by using your User model.
If you can configure your User model and users table correctly , you should be able to get all records from your users table like this :
$users = User::all();
Then you can filter it like :
$users = $users->where('gender','male') // where('gender',$request->gender) in your situation
If you dont have a users table or a model , you can look to the document about how to create models using artisan commands Laravel API Doc. Generating Model Classes

How Do I Append Additional Yii 1.16 ActiveRecord Models?

I am familiar with using Yii to call records, but how would I go about taking an existing active record model and appending more information to it using a different query?
For example:
$user = User::model()->findByPk(1);
$user[] = User::model()->findByPk(2);
Basically, I am trying to add model $user1 + $user2. In this type of example, I want to have both users 1 and 2 in the same $user model. (I have not actually tried the code above, but I do not think it would work like that.) The information obtain from both requests would be exactly the same format.
Be aware that that I am not trying to get both users. I know how to do that. In this question, I am attempting to take an existing model and add more data to it to form one model by merging the two models together.
There is no built in Yii way to do what you are trying to accomplish. Instead, you can your model with some custom enhancements.
private $additionalUsers = array();
public function addAdditionalUser($user)
{
$this->additionalUsers[] = $user;
}
public function getAdditionalUsers()
{
return $this->additionalUsers;
}
Then you use this as follows:
$user = User::model()->findByPk(1);
$user->addAdditionalUser(User::model()->findByPk(2));
However, without knowing more of what you mean by "merge" the models, this may or may not be what you are looking for. An example of how you expect to use the merged model would be useful if this answer doesn't suit your needs.
You can do this:
$users = array();
$user1 = User::model()->findByPk(1);
$user2 = User::model()->findByPk(2);
array_push($users, $user1);
array_push($users, $user2);
Now $users is an array that contains two objects.
You can use
$users = User::model()->findAllByPk(array(1,2));
which will return and array of usermodels

Kohana ORM Update not working

I have discovered Kohana just 2 days ago and, after facing a few problems and managing to deal with them, I ran into a quite strange one.
When I try to update an entry in DB, instead of updating the entry ORM just inserts a new row.
Everything is similar to this example http://kohanaframework.org/3.0/guide/orm/examples/simple
My code (controller file):
class Controller_Admin extends Controller {
...
public function action_test($id)
{
$inquiry = ORM::factory('inquiry')->where('Id', '=', $id)->find(); // $inquiry = Model_Inquiry($id) doesn't work, too
$inquiry ->Name = 'Someone';
$inquiry ->save();
}
...
}
Model file:
class Model_Inquiry extends ORM
{
protected $_table_name = 'mytable';
}
Do you have any ideas why it's inserting a new entry instead of updating the old one? I read that it's because the ID is not correctly set, but I tried using a fixed value (->where('Id', '=', 5)) and it didn't work (it still inserted a new row).
Thanks in advance!
Your record isn't loaded in the first place. To check if it's loaded, do:
if ($inquiry->loaded()){...
Also, you can check what query has been run by doing:
echo $inquiry->last_query();
So you can manually check what exactly is being returned to ORM.
The main problem here is that you're using save() instead of being more strict and using create() / update(). If you used update(), ORM would throw an exception complaining about the record not being loaded.
Save is basically a proxy to these methods, relying on the loaded state.
(I assume that you're using Kohana 3.1 since 3.0 ORM doesn't have separate update / create methods at all)

Categories