I'm using CodeIgniter to build a website, and I want to show a list of construction projects from a database table, which we will simply call project_table. For each project I also have an address, stored in another table, address_table, each address has a project_id, which links it to a project.
I have made a function, get_projects, in my projects model, which is used to get the project information and pass it to the project view, like such:
public function index() {
$data['projects'] = $this->project_model->get_projects();
$data['title'] = 'Ejendomme';
$this->load->view('templates/header', $data);
$this->load->view('projects/index', $data);
$this->load->view('templates/footer');
}
My question is how I get the addresses read, linked to the correct projects, and shown. I suppose I could make a function which is called from the view, which loads the address based on project_id, but as I understand it, this is really bad practice. Is there a way to call a get_address function from the controller, and pass it on to the view, without losing track of which address belongs to which project?
Update:
Per request here is the function get_project(), which gets the project information from the database. I have considered calling a get_address() function inside this, but I am not sure how I would return the addresses from the function.
// Function to read all projects from database
public function get_projects() {
$query = $this->db->get('project_table');
return $query->result_array();
}
Was more useful if you've posted the get_projects method from models. Anyway, the trick is to make use of Model-View-Controller(MVC) architecture, therefore you put into the model the selection from database.
Here is an example with a method to extract your data from those two tables:
public function get_projects()
{
//for standard mySQL
//select only the db fields that you need
$query = "SELECT pt.*, at.* FROM project_table as pt, address_table as at WHERE pt.project_id = at.project_id";
$db_result = $this->db->query($query);
$result_object = $db_result->result();
/*
here you can add a check for the result (for instance to check if the return is not empty)
*/
return $result_object;
}
Now parse the result to a view and play from there with the data.
Joining the ideas in the previous answers, you could use the query builder (using CI 3 name) to join the two tables and return all the information you need from that method in the model:
public function get_projects() {
$this->db->from('project_table');
$this->db->join('adress_table', 'adress_table.project_id', 'project_table.id');
return $this->db->get()->result_array();
}
You can learn more about the QueryBuilder Class at the documentation.
Ideally you want to keep all your database queries in the model. You can call other functions in your model by using $this->function_name().
I believe this will achieve what you are after (these go in your model):
// Function to read all projects from database
public function get_projects() {
$results = $this->db->get('ed_projects')->result();
foreach($results as $r) {
$r->address = $this->get_address($r->id);
}
return $results;
}
// Function to read addresses for a $project_id
private function get_address($project_id) {
return $this->db->from('project_address_table')
->where('project_id', $project_id)
->get()->result();
}
I would also recommend using the codeigniter active record class (http://www.codeigniter.com/user_guide/database/active_record.html) for doing easy database queries like this as it makes it a lot easier to see what your query is doing
Related
I am struggling with gridview filter. In my code I have two getters.
public function getPhone()
{
return UserPhone::find()->where(['user_id' => $this->id])->orderBy('updated_at DESC')->one();
}
public function getDevice()
{
return ExternalAPiHelper::getDeviceInfo($this->id); // this will make a call to external db, and fetching result from there.
}
I am trying to do a filter for $user->phone->country and $user->device->type I am not sure how I can get the results from both of these in a clean manner. Currently, I am fetching the id from the above 2 and then using the result array in $query->where(['in', 'id', $ids]);
Is there any better way to do this?
use hasMany or hasOne method for relation as per requirement
public function getPhone(){
return $this->hasOne(UserPhone::className(),['user_id' => 'id'])
->orderBy('updated_at DESC');
}
than add this relation in main query where you want to apply filter
$query = ....Model query where you define above relations
$query->joinWith('phone')
$query->andWhere(['LIKE','country',$countryName])
explore more about yii2 relations
Database
I'm kind of new to databases and I made this small database, but I have problems fetching data from it.
Im trying to get all the racers from the logged in user, and it works properly, but if I enter $pigeons = $user->racer I only get back the racer table. I would like to know the attributes of the racers from the pigeons table aswell. I've made it work with query builder left joining the tables but I'm not sure why I set up this relationship if I can't use Laravel inner method.
In the User model I have these relationships:
public function pigeons(){
return $this->hasMany('App\Pigeon');
}
public function racers(){
return $this->hasManyThrough('App\Racer', 'App\Pigeon');
}
This is the Pigeon model:
public function user(){
return $this->belongsTo('App\User');
}
public function racer(){
return $this->hasMany('App\Racer');
}
}
And this is the Event model:
public function race(){
return $this->hasOne('App\Race');
}
public function racers(){
return $this->hasMany('App\Racer');
}
And this is what my EventsController looks like with the working alternative method and the commented not working.
public function upcoming(){
$id = auth()->user()->id;
$user = User::find($id);
$pigeons = DB::table('racers')->leftJoin('pigeons', 'racers.pigeon_id', '=', 'pigeons.id')->where('pigeons.user_id', '=', $id)->get();
//$pigeons = $user->racers;
return view('events.upcoming')->with('pigeons', $pigeons);
}
This is what I get with $user->racers or $user->racers()->get():
[{"id":1,"pigeon_id":14,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null},{"id":2,"pigeon_id":15,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null},{"id":3,"pigeon_id":16,"user_id":4,"event_id":1,"position":0,"created_at":null,"updated_at":null}]
And this is what I want to get, its not correct either since I should get id:1 but I want to pass to view these additional datas aswell like gender, color, ability (but they are in pigeons table not in racers).
[{"id":14,"pigeon_id":14,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"hen","color":"blue","ability":38},{"id":15,"pigeon_id":15,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"hen","color":"blue","ability":48},{"id":16,"pigeon_id":16,"user_id":4,"event_id":1,"position":0,"created_at":"2018-09-27 10:01:04","updated_at":"2018-09-27
10:01:04","gender":"cock","color":"blue","ability":11}]
To get the pigeons, what you would have to do is $pigeons = $user->racers()->get();. You can see an example of this in Laravel's official documentation https://laravel.com/docs/5.5/eloquent-relationships#introduction.
This is my Report Model
protected $fillable = [
'site_url',
'reciepients',
'monthly_email_date'
];
public function site()
{
return $this->belongsTo('App\Site');
}
This is my Site Model
public function report()
{
return $this->hasMany('App\Report');
}
This is my ReportController
public function showSpecificSite($site_name)
{
$records = DB::table('reports')
->select('email_date','url','recipient')
->whereHas('sites', function($query){
$query->where('site_name',$site_name);
})
->get();
return view('newsite')->with('records',$records)
->with('site_name',$site_name);
}
My Controller is not yet working as well.
The thing is I would like to copy all the three files from sites table to reports table.
Is it possible in insertInto ?
My code on ReportController shows you that I'm selecting data from reports table but I am the one who puts data to reports table to see the output but it is not yet working because of the it cant reach out the value of site_name even though I already put a relationship between the two tables.
You're not actually using Eloquent in your controller you're just using the Query Builder (DB). This will mean that you don't have access to anything from your Eloquent models.
Try:
$records = \App\Report::whereHas('site', function($query) use($site_name) {
$query->where('site_name', $site_name);
})->get(['id', 'email_date', 'url', 'recipient']);
I've added id to the list of columns as I'm pretty sure you'll need that to use whereHas.
NB to use a variable from the parent scope inside a closure you need to pass it in using use().
I've got two models, User and Seminar. In English, the basic idea is that a bunch of users attend any number of seminars. Additionally, exactly one user may volunteer to speak at each of the seminars.
My implementation consists of a users table, a seminars table, and a seminar_user pivot table.
The seminar_user table has a structure like this:
seminar_id | user_id | speaking
-------------|-----------|---------
int | int | bool
The relationships are defined as follows:
/** On the Seminar model */
public function members()
{
return $this->belongsToMany(User::class);
}
/** On the User model */
public function seminars()
{
return $this->belongsToMany(Seminar::class);
}
I am struggling to figure out how to set up a "relationship" which will help me get a Seminar's speaker. I have currently defined a method like this:
public function speaker()
{
return $this->members()->where('speaking', true);
}
The reason I'd like this is because ultimately, I'd like my API call to look something like this:
public function index()
{
return Seminar::active()
->with(['speaker' => function ($query) {
$query->select('name');
}])
->get()
->toJson();
}
The problem is that since the members relationship is actually a belongsToMany, even though I know there is only to ever be a single User where speaking is true, an array of User's will always be returned.
One workaround would be to post-format the response before sending it off, by first setting a temp $seminars variable, then going through a foreach and setting each $seminar['speaker'] = $seminar['speaker'][0] but that really stinks and I feel like there should be a way to achieve this through Eloquent itself.
How can I flatten the data that is added via the with call? (Or rewrite my relationship methods)
Try changing your speaker function to this
public function speaker()
{
return $this->members()->where('speaking', true)->first();
}
This will always give you an Item as opposed to a Collection that you currently receive.
You can define a new relation on Seminar model as:
public function speaker()
{
return $this->belongsToMany(User::class)->wherePivot('speaking', true);
}
And your query will be as:
Seminar::active()
->with(['speaker' => function ($query) {
$query->select('name');
}])
->get()
->toJson();
Docs scroll down to Filtering Relationships Via Intermediate Table Columns
Something very basic but I'm having a hard time solving this.
I have a list of users in the database that show as online users. I am fetching these users by their user_id
Model
public function scopeloggedInUser($query){
return $query->select('user_id')->get();
}
when I var_dump or dd it shows that its a collection of a list of currently logged in users. (Said it was super simple).
I need to fetch those individual users. How do I dilute this to the individual user within the Online Model.
Within the Controller
public function index(Online $online)
{
$activeuser = $online->loggedInUser();
return view('user.user', compact('activeuser'));
}
In your online-model specify a relationship to the real user like this:
public function user()
{
return $this->hasOne('App\User');
}
In your view you can now access each user in your foreach-loop like this:
foreach ($activeusers as $user)
{
echo $user->user->username; // or whatever fields you need
}
But to be honest: in your case I wouldn't set up a new database table and new model if you need this functionality.
Move your logic to your User model and add a boolean field to your user table and change your query-scope to this (again: in your user model)
public function scopeOnline($query){
return $query->where('online', 1);
}
You also shouldn't do a get() within a scope because then you have no more access to the query builder. For example: you want all logged in users that are female.
With get: not pretty.
Without get:
User::online()->where('gender', '=', 'female')->get();