laravel 5.2 work with belongs to with two different queries - laravel

I have write down this query
Controller
$data = User::where('name',$name)->with('country');
In User model
function country () {
return $this->belongsTo('App\Country');
}
In view
echo $data->country->name;
It is working fine but it run 2 queries :(
Select * from user where name = "xyz"
Select * from country where id = "745"
I want to stop this, I want to fetch data with one query only. Join is the solution, Is any other solution for this?

Unfortunately this is the way Eloquent works. It uses two queries because it's a simpler task to initialise your models and to avoid column naming conflicts.
If you are concerned about performance but still want some sort of querying tool, use the Query Builder shipped with Laravel.
To answer your question, joins will be your best bet.

$data=user::with('country')->where('id',745)->where('name','xyz')->get();
i hope that will help you

Related

Laravel Search Model

Im new to laravel and have completed a project on the latest version laravel 5.6
However, the only thing that is pending to learn and implement is the search functionality which is the core of every application. The application i have coded is a huge project and i do not want to mess it up so would like to learn how search functionality works in order to implement in multiple sections of the project.
Let's say i have a the following models 1.Country 2.State 3.City 4.Professional_Categories 5.Professionals and i have added the relations in the models accordingly
I fetch the records normally using the following code
public function index()
{
$categories = ProfessionalCategory::all();
$topprofessionals = Professional::where('status', 1)->limit(12)->get()->sortByDesc('page_views');
$professionals = Professional::where('status', 1)->latest()->paginate(9);
return view('professionals.index',compact('professionals', 'categories', 'topprofessionals'));
}
I can pull up Countries, States and Cities as i pulled in categories and with foreach i can display them in the select box. Or i could use pluck('name', 'id') that works good too. But i have never tried search queries.
I want a search form on the professionals page where a user can select country, state, city, category and type keywords in locality and professional name to find the professionals. My next step would be to learn dependent dropdown for country, state and city.
And how the results can be displayed on the view file where im currently fetching records with foreach($professionals as $professional)
I do not need code, but just a basic example on how these kind of things work in laravel. Once i learn the basics i want to implement auto suggest from database and things like that. And a single form to search all the models.
It sounds like you'll need full text searching across a number of tables and associated columns. I'd recommend using Laravel Scout or a similar service (such as elastisearch) for this.
These will index your records in a way to allow for fast and efficient fuzzy searching. Using Scout as an example, you can directly query on your models like:
$orders = App\Order::search('Star Trek')->get();
Searching with Scout
This will save you from writing numerous queries using LIKE which becomes very slow and inefficient quite quickly.
Using Eloquent you might do something like this in your Controller:
public function search(Request $request)
{
$countries = Country::where('name', 'like', '%' . $request->search_value . '%')->get();
}
This will return the countries whose name contains the search_value provided by the user.

Where to process data in Laravel

Back when I was using CodeIgniter I had functions in my models like
public function GetArticlesFormatted($inactive = FALSE)
and then in my controller I could have had
$articles->GetArticlesFormatted(true);
And so on.
How should I achieve the same with Laravel 5.4? The database of the app I'm building is already built and full and is a mess so most of the "automated" super-restrictive things that Laravel has don't work out of the box.
For example there is a Country Code that I'm retrieving and I need it as is, but in some instances I need it converted in a Country Name which I had in another table.
Right now I just have in my controller wherever I am retrieving data from the model:
$countryResult = Country::where('country_code', $item['country_code'])->first();
$countryArray = $countryResult->toArray();
$item['country'] = $countryArray['country_name'];
Can I somehow achieve that in a more elegant way?
I tried accessors but for some reason couldn't get anything to work for my purposes.
A select query can be used to limit selection to a particular column.
$countryName = Country::select('country_name')
->where('country_code', $item['country_code'])
->first();

Laravel 5.3 Pulling comments from the fields of a DB table

Simple question here:
In laravel 5.3 how would I pull the comments from a database table? Is there a clean way of doing it using some of the out-of-the-box features that laravel provides??
Thank you in advance.
Laravel 5.2-5.3, as far as I know, comes with a built-in package called doctrine that allows you to interact with a lot more within a database and it's tables than eloquent. I believe the framework members will eventually add more to the system so you can make more dynamic use of a DB and tables etc.
For the time being this is how I implement accessing the structure (comments included) of a database table:
$settings = SomeModel::where($items_match)->get(); //Making use of Eloquent
$columns = DB::connection('database_name_here')
->getDoctrineSchemaManager()
->listTableDetails('table_name_here');
foreach ($settings as $key => $value) {
if ($comments[$key] = $columns->getColumn($key)->getComment()) {
}
}
It's fairly clean and get's the job done. The only downside I see is it's a double hit to the DB which I'm thoroughly against, I'm working on a way to combine the 2 implementations in laravel so that it's only 1 query doing both jobs.

Linq security - hide columns

I am struggling a bit on what probably is a simple matter or something I misunderstand... But anyway, using Linq entity code first, I am trying to keep some of my tables to be inaccessible from the client, without success.
Using Breeze, I have made a datacontext that holds only the dbsets I want exposed, fine.
But when I write a query using .expand(). For example, let's say I have a posts table which I want to expose, and an Owner table that I want to hide.
Using a query like:
var query = EntityQuery
.from('Posts')
.expand('Owner');
I can still see all the columns from Owner.
So the question is: in Linq, how am I supposed to secure/protect/hide the tables, and/or specific columns, that I want to hide?
After some digging, all I have found is the [JsonIgnore] attribute, which seems insufficient to me.
What is the best way to do this? I feel I am missing something probably huge here, but it's the end of the day around here...
Thanks
If you are using the Breeze's WebApi implementation then Breeze also supports ODataQueryOptions ( see here and here ).
This allows you to mark up your controller methods so as to limit how the query is interpreted. For example, to only allow filtering on your 'Posts' query and therefore exclude the ability to "expand" or "select" 'Owners' from any 'Posts' request you could do the following.
[Queryable(AllowedQueryOptions=AllowedQueryOptions.Filter| AllowedQueryOptions.Top | AllowQueryOptions.Skip)]
public IQueryable<Posts> Posts() {
....
}
Ok apparently my question was already addressed here:
Risks of using OData and IQueryable
I just found it.

Code Igniter Model To Model Relationship

In CI, how do you relate each other the models?I have four models right now Users, UsersDepartment, UsersToDepartment, UserStatus and I need to join those four models to be able to pick up all the data.
I have this code in my controller to pick all users data from the Users Table:
function view($user_id){
$data['user'] = $this->User_model->get_by_id($user_id)->row();
}
The user_status saved in the Users Table is only the status_id so I need to connect to the UserStatus table to get the equivalent name of the users_status_id. I need to know the list of group of which the user belongs to. So I need to get it from the UsersToDepartment Table based on the Users.userid. Then get the equivalent groupname in the UsersDepartment Table. Please see my diagram to explain further.
I know in the native PHP, this can be done by using join. How is that done in CI?
I know with yii, you can do it this way
$posts=Post::model()->with(
'author.profile',
'author.posts',
'categories')->findAll();
Is this possible with CI too?
example u have table_one and want to join table_two using their id
$this->db->select('columns');
$this->db->from('table_one');
$this->db->join('table_two', 'table_two.id = table_one.id');
//then do the query
you can read this link below for more complete tutorial :
https://www.codeigniter.com/userguide2/database/active_record.html
code igniter is not a ORM framework for php...
you can not treat it like ORM frameworks(Laravel is good example for ORM frameworks).
but you can simulate that with join on query.
this work just get you the others models data and not get you those models object ...
Refer to $this->db->join(); heading in Active Record: CodeIgniter
I know codeigniter is not that good here. So I always prefer Yii over it.
Try use this query of joining table
Select a.*,b.*
from table_one a
inner join table_two b where b.id=a.id

Resources