how to insert postgresql into laravel model - laravel

I have a postgresql code like this and it runs correctly but I'm confused to enter the laravel model
postgresql :
select * from anggota a where id_parpol = 4 and a.nik in ('2816742691102816','8939799808489659','4757527446829790') or a.no_kta in ('2816742691102816','8939799808489659','4757527446829790')
anggotaContoller :
$aa = "2816742691102816,8939799808489659,4757527446829790";
$bb = explode(",", $aa);
$model = Anggota::where('id_parpol', Auth::user()->id_org)->whereIn('nik', $bb)->whereIn('no_kta', $bb)->get();
dd($model);

You can use closure based grouping of queries
$model = Anggota::where('id_parpol', Auth::user()->id_org)
->where(function($query) use($bb){
$query->whereIn('nik', $bb)
->orWhereIn('no_kta', $bb);
})->get();

Related

Laravel eloquent whereIn with one query

In laravel, I can use many where rules as an array a run one query to the database using laravel eloquent where method to get needed result.
Code:
$where = [];
$where[] = ['user_id', '!=', null];
$where[] = ['updated_at', '>=', date('Y-m-d H:i:s')];
if($request->searchTerm) {
$where[] = ['title', 'like', '%' . $request->searchTerm . '%'];
}
Model::where($where)->get();
Question part:
Now I need to use Laravel Eloquent method whereIn with array params to get needed result with one query.
I tried by looping method but with many queries to the database.
Code:
$model = new Model;
$whereIn = [];
$whereIn[] = ['date', '>=', Carbon::now()->subDays(10)];
$whereIn[] = ['user_role', 'candidate'];
if (!empty($scope) && is_array($scope)) {
$whereIn[] = ['user_id', $scope];
}
if(is_array($employment) && !empty($employment)) {
$whereIn[] = ['employment', $employment];
}
if(is_array($experience) && !empty($experience)) {
$whereIn[] = ['experience', $experience];
}
foreach ($whereIn as $v) {
$model = $model->whereIn($v[0], $v[1]);
}
dump($model->get());
First I tired $model->whereIn($whereIn)->get() but it's return error. It's possible get results with one query using whereIn without looping?
Note: My $whereIn array will be dynamic array!
whereIn is a query builder function so you can't use it on the model directly. Instead you should create a query builder instance. I also suggest you use when instead of the if statements:
$models = Model::when(!empty($scope) && is_array($scope), function ($query) use ($scope) {
$query->whereIn('user_id', $scope);
})->when(!empty($employment) && is_array($employment), function ($query) use ($employment) {
$query->whereIn('employment', $employment);
})->when(!empty($experience) && is_array($experience), function ($query) use ($experience) {
$query->whereIn('experience', $experience);
})->get();
dump($models);
when essentially runs the function when the first parameter is true. There's more detail in the documentation under conditional clauses.
Since your $whereIn variable is an array of arrays it will work like :
$model->whereIn($whereIn[0][0], $whereIn[0][1])->get();
If it just a simple array then you can use :
$model->whereIn($whereIn[0], $whereIn[1])->get();
Do in Eloquent
$model = Model::whereIn('id', array(1, 2, 3))->get();
Or using Query builder then :
$model = DB::table('table')->whereIn('id', array(1, 2, 3))->get();

How to get data based in comparing value in pivote table with value in required table in laravel 5.6?

I am learning larvel 5.6 so I am trying to retrieve number of messages that have id larger than last_seen_id in pivot table
I have user table which have the default columns generated by:
php artisan make:auth
and messages tables which have the following columns:
id, from, message_content, group_id
and the group table have the columns:
id,type
now there is many to many relation between the users and groups table through the custom pivot table which have the columns:
group_id,user_id,last_id_seen
now if I want to retrieve the messages which belong to same group and have larger id than last_id_seen in the pivot table how to do it?
I think you are looking for something like this:
$groupId = 1; // set to whatever you want
$lastSeenId = \Auth::user()->groups()
->where('group_id', $groupId)
->first()->pivot->last_id_seen;
$messages = Message::where('id', '>', $lastSeenId)->get();
A more robust version, which does not fail when your user does not have an entry for the group yet, would be:
$groupId = 1; // set to whatever you want
$group = \Auth::user()->groups()->where('group_id', $groupId)->first();
$lastSeenId = $group ? $group->pivot->last_id_seen : null;
$messages = Message::when($lastSeenId, function($query, $id) {
$query->where('id', '>', $id);
})->get();
Note: normally you'd use optional() in the second snippet, but Laravel 5.2 does not come with this helper...
If you want both the count() of the results and the results themselves, you can store the query in a variable and perform two queries with it. You then don't have to rewrite the same query twice:
$groupId = 1; // set to whatever you want
$group = \Auth::user()->groups()->where('group_id', $groupId)->first();
$lastSeenId = $group ? $group->pivot->last_id_seen : null;
$query = Message::when($lastSeenId, function($query, $id) {
$query->where('id', '>', $id);
});
$count = $query->count();
$messages = $query->get();

Laravel select * where id =(select id )

Using Laravel eloquent how do I make a query like this:
select * from branches where user_id =(select id from users where name ='sara' )
Assuming that you have a user relationship in your Branch model you could use whereHas:
$branches = Branch::whereHas('user', function ($query) {
$query->where('name', 'sara');
})->get();
Update
If you're using v8.57.0 or above, you can now use the whereRelation() method instead:
Branch::whereRelation('user', 'name', 'sara')->get();
$id = Users::select('id')->where('name','sara')->first();
$barnches = branches::where('id',$id)->get();
Here Users and branches are models , first is using for 1 row and get for many rows
I would split it into two queries. First getting the id, then getting the list. Expecting your models to be called "User" and "Branches"
$user = User::where('name', 'sara');
$id = $user->id;
$branches = Branch::where('id', $id);
This site may help you Link
Try this.
$name = 'sara';
$results = BranchModel::whereIn("user_id", function ($query) use ($name) {
$query->select("id")
->from((new UserModel)->getTable())
->where("name", $name);
})->get();
You can use this:
$users = User::whereName("sara")->get()->pluck('id');
Branch::whereIn('user_id',$users)->get();

Laravel load only Model

I want to load only the model to be able to add wheres etc later.
$query = Users;
if($request->filter == 1) {
$query = $query->where('user_access', 'admin');
}
if($request->otherFilter == 1) {
$query = $query->where('user_email', '');
)
$query->get();
Although using $query = Users; doesn't work..?
You can use it by creating a Illuminate\Database\Eloquent\Builder instance as:
$query = Users::query();
and then you can add further queries in query builder instance.
You can just create an instanse of the Users model with:
$query = new Users;
And then work with it.
You should really consider using local query scopes with Eloquent if you are planning to do lots of different queries.
Laravel Eloquent Query Scopes
//App\User.php
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
$users = App\User::popular()->orderBy('created_at')->get();
You can create custom queries instead of long verbose ones.

How to connect the Db and get the data from table in Joomla php

I want to connect the Joomla DB and i have created table in PHPmyAdmin.
And want to get the row and values from the field.
Best way when having a proper JTable:
$row =& JTable::getInstance('my_table', '');
$row->load($id);
When working without JTable:
$db = &JFactory::getDbo();
$sql = 'SELECT * FROM #__table WHERE id ='.$id;
$db->setQuery($sql);
$object = $db->loadObject();
OFC you can make that more elegant inside MVC. BUT for starters maybe enough.
$db = JFactory::getDBO();
$query = "select id,title from #__content";
$db->setQuery($query);
$result = $db->loadObjectList();//here we got array of stdClass===prepared objects in PHP 5.3
foreach($result as $res){
echo $res->id."".$res->title;
}

Resources