I'm new to laravel, so I'm searching for how to send a specific id to the controller in order to get data from another table ?
For example
while($shipment = sqlsrv_fetch_array($get_customer_rule,SQLSRV_FETCH_ASSOC)) {
//display some data ......
// inside the loop i will have another query to get data from another table has //relation with shipment table
$id = $shipment['id'];
$customer = "SELECT * FROM [ccctadm].[customer] WHERE id = '$id' ";
$get_customer_info = sqlsrv_query($conn, $customer);
$get_customer_id = sqlsrv_fetch_array($get_customer_info,SQLSRV_FETCH_ASSOC);
$customer_id = $get_customer_id['customerid'];
}
I can't write query in while loop in laravel, so how can I pass shipment id to the controller so I can get customer data related to the shipment
Since you are new to Laravel, maybe you should learn the Laravel way first. Watch this video on how to work with Eloquent and perhaps every other video in that series. https://laracasts.com/series/laravel-from-scratch-2017/episodes/7
Once you get your head around that, you will be able to rewrite your query as
$shipments = Shipement::all();
foreach( $shipments as $shipment ) {
$customer = $shipment->customer;
$customer_id = $customer->id;
}
Even better when you get a bit further with laravel and be able to work with eager loading, you will just do
$shipments = Shipment::with('customer')->get();
And in your view
#foreach($shipments as $shipment)
Customer ID is : {{ $shipment->customer->id }}
#endforeach
You have decided you to work with Laravel. Take advantage of it. It will make everything easier and speed up your development process.
If you want to stick to your raw SQL queries, you can use the query builder
$result = DB::select("SELECT * FROM [ccctadm].[customer] WHERE id = ?", [$id]);
And work with the result
Related
I need your help to build a query in Laravel either eloquent or DB query would do too.
My table name is Users
To see the DB structure, open the following link:
https://jsfiddle.net/vardaam/mvqzpb2j/
Every user row has 2 columns referral_code and referred_by_code which means every user can refer to someone and earn bonus similarly the same user was also been referred by some one.
I would like to return the information on page with loop in users details along with Username of the user who had referred him to this. To track the same I created those 2 columns in the same table i.e.: referral_code and referred_by_code.
I do not know how to write this in 1 query or how to combine 2 queries and get the desired results.
My controller code looks like below:
$obj_users = User::get();
$codes = [];
$referrers = [];
foreach( $obj_users as $referred_by_code )
{
//Following fetches all user's referred_by_code's code
$codes[] = $referred_by_code->referred_by_code;
}
foreach ($codes as $code)
{
//Following fetches usernames of the given referred_by_code's codes
$referrers[] = User::where('referral_code', $code)->first()->username;
}
return view('users.users', compact(['users', 'paginate', 'referrers']));
The returning $users variable provides me loop of users data but I do not know how to attach those referrer's username to that object.
I tried my level best to describe, please ask incase what I said doesn't make sense, will be happy to provide further clarification.
Best
You can add into your User model the following relationship:
public function referredBy()
{
return $this->belongsTo(User::class, 'referred_code', 'referral_code');
}
In your controller you can use:
$users = User::with('referredBy')->get();
return view('users.users', compact('users'));
and later in your view you can use:
#foreach ($users as $user)
{{ $user->username }} referred by {{ $user->referredBy ? $user->referredBy->username : '-' }}
#endforeach
So recently I have been thinking and can't find a solution yet to this problem since my lack of development with doctrine2 and symfony query builder.
I have 2 tables:
Goals: id,user_id,target_value...
Savings: id,goal_id,amount
And I need to make a select from goals (all the informations in my table are from the goals table, except that I need to make a SUM(amount) from the savings table on each goal, so I can show the user how much did he saved for his goal)
This is the MySQL query:
select
admin_goals.created,
admin_goals.description,
admin_goals.goal_date,
admin_goals.value,
admin_goals.budget_categ,
sum(admin_savings.value)
from admin_goals
inner join admin_savings on admin_savings.goal_id=admin_goals.id
where admin_goals.user_id=1
group by admin_goals.id
It returns what I want but I have no idea how to implement it with doctrine or query builder, can you please show me an example in both ways?
I highly appreciate it !
I am going to assume you need this fields only and not your AdminGoals entity. On your AdminGoalsRepository you can do something like this:
public function getGoalsByUser(User $user)
{
$qb = $this->createQueryBuilder('goal');
$qb->select('SUM(savings.value) AS savings_value')
->addSelect('goal.created')
->addSelect('goal.description')
->addSelect('goal.goalDate')
->addSelect('goal.value')
->addSelect('goal.budgetCat') //is this an entity? it will be just an ID
->join('goal.adminSavings', 'savings', Join::WITH))
->where($qb->expr()->eq('goal.user', ':user'))
->groupBy('goal.id')
->setParameter('user', $user);
return $qb->getQuery()->getScalarResult();
}
Keep in mind that the return object will be an array of rows, each row is an associated array with keys like the mappings above.
Edit
After updating the question, I am going to change my suggested function but going to leave the above example if other people would like to see the difference.
First things first, since this is a unidirectional ManyToOne between AdminSavings and AdminGoals, the custom query should be in AdminSavingsRepository (not like above). Also, since you want an aggregated field this will "break" some of your data fetching. Try to stay as much OOP when you are not just rendering templates.
public function getSavingsByUser(User $user)
{
$qb = $this->createQueryBuilder('savings');
//now we can use the expr() function
$qb->select('SUM(savings.value) AS savings_value')
->addSelect('goal.created')
->addSelect('goal.description')
->addSelect('goal.goalDate')
->addSelect('goal.value')
->addSelect('goal.budgetCat') //this will be just an ID
->join('savings.goal', 'goal', Join::WITH))
->where($qb->expr()->eq('goal.user', ':user'))
->groupBy('goal.id')
->setParameter('user', $user);
return $qb->getQuery()->getScalarResult();
}
Bonus
public function FooAction($args)
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
//check if user is User etc depends on your config
...
$savings = $em->getRepository('AcmeBundle:AdminSavings')->getSavingsByUser($user);
foreach($savings as $row) {
$savings = $row['savings_value'];
$goalId = $row['id'];
$goalCreated = $row['created'];
[...]
}
[...]
}
If you use createQuery(), then you can do something like this:
$dqlStr = <<<"DSQL"
select
admin_goals.created,
admin_goals.description,
admin_goals.goal_date,
admin_goals.value,
admin_goals.budget_categ,
sum(admin_savings.value)
from admin_goals
inner join admin_savings on admin_savings.goal_id=admin_goals.id
where admin_goals.user_id=1
group by admin_goals.id
DSQL;
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery($dqlStr);
$query->getResult();
On the other hand, if you would like to use createQueryBuilder(), you can check this link: http://inchoo.net/dev-talk/symfony2-dbal-querybuilder/
So I trying to build a notification system (CodeIgniter) and not store it in my database by this unique ID. Now I got some problem to using `SELECT query.
Also this is array stored in "value" row:
[{"id":0,"user_id":"1","comment":"That's a Nice Video.","posttime":1403523177,"status":1},{"id":1,"user_id":"4","comment":"Nice to see this..!!","posttime":1403590409,"status":1}]
And this is my (not work) query:
$query = $this->db->get_where('post_meta',array('status'=>1),in_array('user_id', $id));
Ideas?
Note: Notification will be sparated by "user_id".
You should not use in_array('user_id', $id) on that function because it returns boolean.
On the active record page: https://ellislab.com/codeigniter/user-guide/database/active_record.html you can take a look at parameter it takes for get_where() function
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Notice how the third parameter takes $limit which talks about the number of data you'll receive. (Leaving this blank will return you all data).
Some code examples:
If you just want to get the data with status = 1, use the following:
$query = $this->db->get_where('post_meta',array('status'=>1));
If you want to get the data with status = 1 and user_id = $id, use the following:
$this->db->like('value', '"user_id":"'.$id.'"');
$query = $this->db->get_where('post_meta',array('status'=>1));
The solution above is not the best, but it should work.
The $this->db->like() function will create rules to get data in value row which has "user_id":"$id" where $id is the value that you define.
What if I want to get all notifications and group them based on their ID?
I usually get all the data and then use PHP to group them into its own array. I think it's cheaper than relying on database to do that (Correct me if i'm wrong).
So use the first code:
$query = $this->db->get_where('post_meta',array('status'=>1));
Then iterate them using foreach() or whatever you find convenient.
$data = array();
foreach($query as $k=>$v) {
// Run a function to get User ID
$user_id = your_function_here($v->value);
if(!isset($data[$user_id]))
$data[$user_id] = array();
// This is just some example to group them together, you can optimize it to your own liking
array_push($data[$user_id],$v);
}
your_function_here() is your function to get the user_id from value row on your database.
My structure is as simple as
One user -> has many notifications
so to fetch the notifications of the logged in user
I type this on the controller
$notifications = $this->getUser()->getNotifications();
Now I need to paginate the results but since this won't work
$notifications = $this->getUser()->getNotifications()->setMaxResults(2)..
I guess I need to use a createQuery to fetch the results?
what query would be the DQL equivalent of
"$this->getUser()->getNotifications()" ?
You can't limit . Try slice
If you have Doctrine 2.1 you can use ->slice() on the collection:
$notifications = $this->getUser()->getNotifications();
$result = $notification->slice(0, 2);
In my CodeIgniter project I'm getting the list of projects and successfully output them on a page. However, the data in one of the columns on that page should be retrieved from a different table in DB using the project ID. Could anybody help me to figure out how that can be done? Basically I need to make another query to that other table specifying the project id but don't actually know how to do that with CodeIgniter.
UPDATE
In the model I'm getting the list of projects with the following function:
function get_projects_list($page, $limit){
$sql = sprintf("SELECT * FROM Project WHERE deleted != 1 LIMIT %d, %d", ($page-1)*$limit, $limit);
$query = $this->db->query($sql);
return $query->result();
}
And in the controller I call the following function:
$projects_list = $this->Project_management_model->get_projects_list($curPage, self::$LIMIT_PER_PAGE);
$data['projects_list'] = $projects_list;
$data['cur_page'] = $curPage;
$data['page_count'] = $pageCount;
$this->load->view('project_management_view', $data);
And in the view I simply run on the $data with foreach and list the results in a table. In that table there's a column where I need to show a result from another table based on the ID of the project of that very row.
Thanks for helping.
You didn't mention whether you are using ActiveRecord or not. I am assuming that you are. I'll also guess that maybe what you need to do is use a JOIN.
If you were using straight SQL, you would do this using some SQL that might look something like this:
SELECT a.appointment_time, u.user_real_name FROM appointment a, site_user u WHERE u.site_user_id = a.user_id;
That would pull the user's name from the user table based on the user id in the appointment table and put it with the appointment time in the query results.
Using ActiveRecord, you would do something like this:
$this->db->select('appointment_time,user_real_name')->from('appointment')->join('site_user', 'site_user_id=appointment_user_id');
But why don't you tell us a little bit more about your question. Specifically, do you want this column in the other table to be related to the rows from the first table? If so, my JOIN suggestion is what you need.
I've actually found a way to do that with a custom helper. Creating a new helper and loading it in the controller gives an option to use the function from that helper in the view.
Thanks.
public function get data()
{
$this->db->flush_cache();
$query = $this->db->get('project_table');
$result = $query->result();
$data = array();
for ($i = 0;$i < count($result);$i++)
{
$data[$i] = $result[$i];
$data[$i]['project_data'] = temp($result[$i]->id);
}
return data;
}
private function temp($id = 0)
{
$this->db->flush_cache();
$this->where('id',$id);
$query = $this->db->get('project_table2');
$result = $query->result();
if (count($result) != 0)
return $result[0]->data;
}
you can do it by some thing like that,or you can use sub-query by query function of database.