How to join a database from another database laravel - php

So I have this sub-window created and I want to put customer details.
At first, opening the sub-window(without using the search boxes) it returns data, but the data from another database cannot be shown.
Now when I use the search box, it now gives me error of: undefined variable paymentgroup.
first database is: clotho_mercurop_laravel
The other database is: clotho_mercurop_eccube
I suppose my query is wrong but I don't know how to fix.
Here is my code:
public function index_sub_form(Request $request)
{
$keyword = $request->all();
$perPage = 25;
if($keyword) {
$paymentgroup = TPaymentGroup::select('t_payment_group.id',
't_payment_group.payment_group_name',
DB::raw('clotho_mercurop_eccube.getfullAdd(eccube.customer_id) as getAdd'),
't_payment_group.main_customer_id',
'eccube.name01',
'eccube.name02')
->join(\DB::raw('clotho_mercurop_eccube.dtb_customer as eccube'), function($j) {
$j->on('t_payment_group.main_customer_id', '=', DB::raw('eccube.customer_id '));
});
if ($keyword['グループ名']) {
$paymentgroup->where('m_item_detail_category.item_detail_category_name', 'like', '%'.$keyword['グループ名'].'%');
}
if($keyword['代表支払者']) {
$paymentgroup->where('m_item_category.item_category_name', 'like', '%'.$keyword['代表支払者'].'%');
}
$paymentgroup = $paymentgroup->paginate($perPage);
} else {
$paymentgroup = TPaymentGroup::paginate($perPage);
}
return view('pop_up.paygroup_sub_form', compact('paymentgroup'));
}

The following website explains the use of multiple database connections in Laravel: Fideloper: Multiple DB connections in Laravel.
Currently, you're using clotho_mercurop_laravel and clotho_mercurop_eccube as tables, not as databases. Is that correct?

Related

data repeating when two tables are joined in codeigniter

I tried to fetch data using joins and the data is repeating,
The controller code is:
public function searchjobs2()
{
//$id=$_SESSION['id'];
$lan = $_POST["picke"]; //var_dump($id);die();
$value['list']=$this->Free_model->get_jobs($lan);//var_dump($value);die();
$this->load->view('free/header');
$this->load->view('free/searchjobs2',$value);
}
And the model:
public function get_jobs($lan)
{
$this->db->select('*');
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work.login_id = tbl_work_stats.login_id",'inner');
$this->db->where("language LIKE '%$lan%'");
// $this->db->where('tbl_work_stats.login_id',$id);
$this->db->order_by('insertdate','asc');
$query=$this->db->get()->result_array();//var_dump($query);die();
return $query;
}
I have used
foreach ($list as $row){
...
}
for listing.
Using distinct will remove duplicate fields:
$this->db->distinct();
From what I can see, your query has ambiguity, and an error in the join statement, also your where like is part of the problem, I would recommend trying this even do there are some missing info, find out wich field you need to join from the second table.
public function get_jobs($lan){
$this->db->select("tbl_work_stats.*, tbl_work.fields");
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work_stats.login_id = tbl_work.login_id","inner");
$this->db->where("tbl_work.language LIKE", "%" . $lan . "%" );
$this->db->order_by("tbl_work_stats.insertdate","asc");
$query=$this->db->get()->result_array();
return $query;}
do you mean to join on login_id?
I am guessing that is the user logging in and it is the same for many entries of tbl_work_stats and tbl_work.
you didn't post your schema, , but login_id doesn't seem like right thing to join on. how about something like tbl_work.id = tbl_work_stats.tbl_work_id or similar?
also CI $db returns self, so you can do:
public function get_jobs(string $lan):array
{
return $this->db->select()
->from('tbl_work_stats')
->join('tbl_work','tbl_work.id = tbl_work_stats.work_id')
->like('language',$lan)
->order_by('insertdate')
->get()
->result_array();
}

How to query related records only using where clause in laravel?

I tried to search students that belong to particular User/School only using the following the query. I have created one-to-many relationship between User and Students.. Everything seems okay but when I try to search students, it gives me list of students that belong to other Users too.
public function searchStudent(Request $request)
{
$q = $request->q;
$grades = Auth::user()->grades;
$searchPupils = Student::where('user_id','=',Auth::user()->id)->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();
if(count($searchPupils) > 0)
{
return view('add-class', compact('grades'))->withDetails($searchPupils)->withQuery($q);
}
else
{
return view ('add-class', compact('grades'))->withMessage('No Details found. Try to search again !');
}
}
I also tried doing
$searchPupils = Auth::user()->students()->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();
Still it searches for the whole Students table . How should it be done?
the problem is in your query where conditions, use advance where clause as below.
$searchPupils =Student::where('user_id','=',Auth::user()->id)
->where(function($query)use($q){
$query->where('name','LIKE','%'.$q.'%')
->orWhere('email','LIKE','%'.$q.'%');
})->get();

Laravel routing real life use case

I am posting Laravel 5.2 real life routing use case and would like to have an answer for it. Problem: same url structure for multiple different database lookups. Please do not post remarks on how to make easier URL structure, this is the way the structure must be and many sites use it in this segment.
URL structure
domain.com/{slug1}/{slug2}/{slug3}
// e.g. domain.com/cottages/slovakia/cheap
// {slug1} - DB table accommodation_types (20+)
// {slug2} - DB table locations (300+)
// {slug3} - DB table accommodation_categories e.g. cheap etc. (100+)
domain.com/{slug1}/{slug2}
// e.g. domain.com/cottages/cheap OR domain.com/slovakia/cheap
// {slug1} - DB table accommodation_types OR locations
// {slug2} - DB table locations OR accommodation_categories
domain.com/{slug}
// DB table accommodation (10000+ entries)
// or
// accommodation_types OR locations OR accommodation_categories
How would you do it nicely? I have these ideas.
a. Use closure and call appropriate controller after examining url segments?
Route::get('{slug1}', function ($slug1, $slug2 = null, $slug3 = null)
{
// Check accommodation
$object = Accommodation::where('slug', $slug1)->first();
if( !is_null($object) )
{
return app()->make('AccommodationDetailController')->view($object);
}
// Check type
$type = AccommodationType::where('slug', $slug1)->first();
if( !is_null($type) )
{
return app()->make('AccommodationListController')->view($type);
}
// etc.
});
b. Generate thousands of urls by for loop and cache it then?
I appreciate any other great solution
I think the best way is to send all these routes to the same controller action and edit your query according to the parameters that are sent.
For example, this would be your routing file:
<?php
Route::get('{slug1}', 'Controller#getPage');
Route::get('{slug1}/{slug2}', 'Controller#getPage');
Route::get('{slug1}/{slug2}/{slug3}', 'Controller#getPage');
In the controller, you can use Eloquent or the query builder to build the sql query according to the variables you received from the route. Below is a simple example:
<?php
class Controler {
public function getPage($slug1, $slug2 = null, $slug3 = null) {
$models = Model::where(function ($query) use ($slug1) {
$query->where('accomodation_types', $slug1)
->orWhere('location', $slug1);
})
->where(function ($query) use ($slug2) {
if (isset($slug2)) {
// Slug2 query
}
})
->where(function ($query) use ($slug3) {
if (isset($slug3)) {
// Slug3 query
}
})
->get();
}
}

Yii2 viaTable multiple variables

I'm trying to find a number of UserComment using a viaTable on the table called user_comment_user in Yii2. However I can't seem to get my variables/query inserted properly.
Currently I've got two queries set up, to check if (on their own) they achieve the correct result, which they do.
These are the two queries that somehow have to be merged into one:
public function findConversation($id)
{
$query = $this->hasMany(UserComment::classname(), ['id'=>'user_comment_id'])
->viaTable('user_comment_user', ['sender_id'=>'id'], function ($query) use ($id) {
$query->andWhere(['receiver_id'=>$id]);
});
$query2 = $this->hasMany(UserComment::classname(), ['id'=>'user_comment_id'])
->viaTable('user_comment_user', ['receiver_id'=>'id'], function ($query) use ($id) {
$query->andWhere(['sender_id'=>$id]);
});
return $query;
}
The answer was actually much simpler than I had imagined:
public function findConversation($id)
{
$query = UserComment::find();
$query->leftJoin('user_comment_user', 'user_comment_user.user_comment_id=user_comment.id');
$query->where(['receiver_id'=>$this->id, 'sender_id'=>$id]);
$query->orWhere(['receiver_id'=>$id, 'sender_id'=>$this->id]);
$query->orderBy(['created_at'=>SORT_DESC]);
return $query;
}

Laravel multiple table join saved to a variable and running a foreach against it (search function)

I presently have 3 tables: Shows, Genres and Show_Genre (associates the two). I have a search form that submits a series of checkboxes with values into an array based on what genres they selected. Presently I want to associate the Shows table and the Genres table into a variable and run a query against it once for every genre checkbox selected. Then, once the selection is filtered, I can display the resulting Show objects that matched the users parameters.
My present setup is the following
public function searchShows(SearchRequest $request)
{
//$ShowsWithGenres give a collection inside a collection which I can't seem to even access its values without doing a bunch of ugly code using count() in a for loop
$ShowsWithGenres = Show::with('genres')->get();
$genres = $request->name;
if(isset($genres))
{
foreach($genres as $genre)
{
//iterate against the selection repeatedly reducing the number of results
}
}
}
Thanks.
You should use whereHas() and whereIn.
Perhaps something like this should do it:
$shows = Show::whereHas('genres', function($q) use($genre_ids)
{
$q->whereIn('id', $genre_ids);
})->get();
EDIT
Try this, however I'm unsure about the performance.
$query= Show::query();
foreach($genre_ids as $id){
$query->whereHas('genres', function($q) use($id)
{
$q->where('id', $id);
})
}
$shows = $query->get();
Using Eloquents whereHas() function you can query results based on the relation's data. http://laravel.com/docs/5.0/eloquent#querying-relations
public function searchShows(SearchRequest $request)
{
// Start a query (but don't execute it at this point as we may want to add more)
$query = Show::with('genres');
$genreNames = (array) $request->name;
// Check there are some genre names, if theres not any it'll cause an SQL syntax error
if (count($genreNames) > 0)
{
$query->whereHas('genres', function($subQuery) use ($genreNames)
{
$subQuery->whereIn('genre_name', $genreNames);
}
}
// Finally execute the query. $shows now contains only shows with the genres that the user has searched for, if they didn't search with any genres, then it contains all the results.
$shows = $query->get();
}

Categories