Laravel 8 removing qoute on the sql - sql

Hi i just wanna know if what i did wrong
this my function
public function fetchJobs(Request $request){
$id = (int)$request->input("id");
$jobs = DB::table('job')
->select('job.*')
->where('job.status', '=', 0)
->Where('application.applicant','=' ,null)
->leftJoin('application', function($join) use ($id)
{
$join->on('application.job', '=', 'job.id');
$join->on('application.applicant','=',$id);
})
->toSql();
return $jobs;
}
this is the result
select `job`.* from `job`
left join `application` on `application`.`job` = `job`.`id` and `application`.`applicant` = `39`
where `job`.`status` = 0 and `application`.`applicant` is null
the error of is that 39 has qoutes is there a way to remove the qoute?

i solved this by adding DB:raw()
public function fetchJobs(Request $request){
$id = (int)$request->input("id");
$jobs = DB::table('job')
->select('job.*')
->where('job.status', '=', 0)
->Where('application.applicant','=' ,null)
->leftJoin('application', function($join) use ($id)
{
$join->on('application.job', '=', 'job.id');
$join->on('application.applicant','=',DB::raw($id));
})
->get();
return $jobs;
}

Related

Unable to insert id of user to another table laravel 8 livewire

I am unable to store user id of another user on my db. I have a messages table, where from_id,t_id and user_id are the foreign key of table users. I have models defined properly as well. The issue I am having is:
can't insert the user_id.
I can save everything else. when i do dd $this->id it shows the corret user id but when it comes to save them i can't.
I tried doing explode and it stopped showing those random values. it now gets the id however in below format: [{"id":3}]
: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: "[{"id":3}]"
As you can see it's getting the user id when i get the values from authenticated user which is obvious.
My code :
public $messages, $sender;
public $users;
public $avatar;
protected $destination = '';
public $messageText;
public function mount($id)
{
$this->id = $id;
$this->avatar = DB::table('users')
->join('messages', 'users.id', '=', 'messages.user_id')
->select('users.id')
->where('users.id', '=', $this->id)->distinct()->get();
$this->destination = DB::table('users')
->join('messages', 'users.id', '=', 'messages.user_id')
->select('users.id')
->where('users.id', '=', $this->id)->first();
$this->users =
Message::latest()
->take(5)
->get()
->sortBy('id');
$this->messages = DB::table('users')
->join('messages', 'users.id', '=', 'messages.user_id')
->select('users.name', 'users.id', 'messages.message', 'messages.created_at')
->where('users.id', '=', $this->id)
->get();
// SELECT * FROM users AS u INNER JOIN messages AS m ON u.ID IN (m.senderID, m.recipientID) WHERE u.ID <> $userID GROUP BY u.ID ORDER BY m.sentAt DESC
}
public function render()
{
// $name = explode(' ', $this->avatar);
// dd($name);
return view(
'livewire.show',
[
'avatar' => $this->avatar,
'messages' => $this->messages,
'users' => $this->users,
]
)->layout('layouts.app');
}
public function sendMessage()
{
$name = explode(' ', $this->avatar);
// $this->validate(['messageText' => "required"]);
$message = new Message();
$message->from_id = Auth::user()->id;
$message->user_id = Auth::user()->id;
$message->to_id = $name[0]; // [{"id":3}]
$message->message = $this->messageText;
// dd($message);
$message->save();
$this->reset('messageText');
}
Error Message:

How to convert Distinct Count SQL query into a Laravel Eloquent query

I would like to convert this SQL query into a laravel eloquent query. So I can create
SELECT
count(distinct article_id) as assigned
FROM
actions
WHERE
action_id = 1 and
set_id = 1
I can translate the query into a raw request which works
DB::table('actions')->select(DB::raw('count(DISTINCT article_id) as assigned'))
->where('action_id', 1)
->where('set_id', 1)
->get();
But I would like to figure out how to do it something like this
$sets = Set::withCount(['actions as assigned' => function ($q) {
$q->distinct()
->select('article_id')
->where('action_id', '=', 1);
}])->get();
or this
$sets = Set::withCount(['actions as assigned' => function ($q) {
$q->distinct('article_id')
->where('action_id', '=', 1);
}])->get();
Eventually I would like to have my Set model contain a scoped method like this
public function scopeWithAssignedCount($query){
$query->withCount(['actions as assigned' => function ($q) {
$q->distinct('article_id')
->where('action_id', '=', 1);
}])
}
So I can add multiple counts to a single call in my controller
$sets = Set::withAssignedCount()
->withUnassignedCount()
->where('palm' => $face)
->get();
Edited per comments
I would like to use something like the below with distinct records.
public function scopeWithAssignedCount($query)
{
$query->withCount(['actions as assigned' => function ($q) {
$q->where('action_id', 1);
}]);
}
Check this query
$count = Set::select('article_id as assigned');
if(!empty($action_id)){
$count = $count->where('action_id', $action_id);
}
if(!empty($set_id)){
$count = $count->where('set_id', $set_id);
}
$count = $count->distinct('article_id')->count('article_id');

Laravel changing the inner join via user input

My Plan is the following.
I have this inner join:
SELECT cd.fk_lend_id,cd.serialnumber ,customers.name,cd.created_at
FROM cd
INNER JOIN customers ON cd.fk_lend_id = customer.lend_id
Where cd.fk_lend_id = 00000000;
This is what it would look like in Laravel:
$scores = DB::table('cd')
->join('cd', 'cd.fk_lend_id', '=', 'customer.lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at')
->where('cd.fk_lend_id',00000000)
->get();
(The created_at stands for the time the customer lend the cd)
->where('cd.fk_lend_id',00000000) <- The zero´s should be replaced with the user input from the inputfield from the view and after the input it should be redirected is this possible?
If it is possible does anyone can give me advice how to do so?
(Edit)
The "yourcds" function:
public function yourcds(Request $request, cds $cd)
{
$this->middleware('guest');
$user_input = $request->userInput
$scores = DB::table('cd')
->join('customers', 'cd.fk_lend_id', '=', 'customer .lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at')
->where('cd.fk_lend_id',$request->$user_input)
->get();
$cds = cd::latest()->paginate(20);
return view('cd.yourcds',compact('cd'))
-> with('i', (request()->input('page', 1) - 1) * 20);
}
The "return" function:
public function return(cds $cd)
{
return view('cd.return',compact('cd'));
}
At first you have to get user input with
$user_input = $request->userInput
Then, just put in your where clause
$scores = DB::table('cd')
->join('cd', 'cd.fk_lend_id', '=', 'customer.lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at')
->where('cd.fk_lend_id', $userInput)
->get();
That's it, no quotation marks needed
EDIT
with your function return the view with form:
public function return(cds $cd) {
return view('cd.return',compact('cd'));
}
Define route to yourcds() method:
Route::post('/yourcds', 'ControllerName#youcds');
In cd.return file place form like this
<form action="/yourcds" method="POST">
#csrf
<input type="text" name="userInput" >
<input type="submit" value="submit" >
</form>
In your method yourcds() palce parameter Requsest:
public function yourcds(Request $request) {
$this->middleware('guest');
$user_input = $request->userInput
$scores = DB::table('cd')
->join('customers', 'cd.fk_lend_id', '=', 'customer .lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at')
->where('cd.fk_lend_id',$request->$user_input)
->get();
$cds = cd::latest()->paginate(20);
return view('cd.yourcds',compact('cd'))
-> with('i', (request()->input('page', 1) - 1) * 20);
}
Hope that's the answer
Just to add the
->join('cd', 'cd.fk_lend_id', '=', 'customer.lend_id')
Should be
->join('customers', 'cd.fk_lend_id', '=', 'customer.lend_id')
function <controller-name>(Request $request){
$myfield = $request->input('<formfieldname>');
$scores = DB::table('cd')
->join('cd', 'cd.fk_lend_id', '=', 'customer.lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at')
->where('cd.fk_lend_id',$myfield)
->get();
}

get values between two dates in silverstripe

i have added two date fields. i want to retrieve the data between those two table.PaymentDate and ChequePostedDate are two fields. so i need to get the rows between two dates.
simply search content have two date fields. i want to retrieve the rows(data) between those two dates
public function __construct($modelClass, $fields = null, $filters = null) {
$fields = new FieldList(array(
DateField::create('PaymentDate','Payment Date : from')
->setConfig('dateformat', 'yyyy-MM-dd')
->setConfig('showcalendar', true)
->setAttribute('placeholder','YYYY-MM-DD')
->setDescription(sprintf(
_t('FormField.Example', 'e.g. %s', 'Example format'),
Convert::raw2xml(Zend_Date::now()->toString('yyyy-MM-dd'))
)),
DateField::create('ChequePostedDate','cr Date : to')
->setConfig('dateformat', 'yyyy-MM-dd')
->setConfig('showcalendar', true)
->setAttribute('placeholder','YYYY-MM-DD')
->setDescription(sprintf(
_t('FormField.Example', 'e.g. %s', 'Example format'),
Convert::raw2xml(Zend_Date::now()->toString('yyyy-MM-dd'))
)),
));
$filters = array(
'PaymentDate' => new PartialMatchFilter('PaymentDate'),
'ChequePostedDate' => new PartialMatchFilter('ChequePostedDate'),
);
parent::__construct($modelClass, $fields, $filters);
}
public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null) {
$dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery);
$params = is_object($searchParams) ? $searchParams->getVars() : $searchParams;
$query = $dataList->dataQuery();
if(!is_object($searchParams)) {
if (isset($params['PaymentDate'])&& $params['ChequePostedDate'] ) {
$query->where('`PaymentNote`.PaymentDate BETWEEN \''.$params['PaymentDate'].' \' AND \''.$params['ChequePostedDate'].'\'');
}
}
return $dataList->setDataQuery($query);
}
}
You can also use WithinRangeFilter something like the following, but you need to use the setMin(), setMax() methods as per this forum response: https://www.silverstripe.org/community/forums/form-questions/show/11685
public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null) {
$dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery);
$params = is_object($searchParams) ? $searchParams->getVars() : $searchParams;
$query = $dataList->dataQuery();
if(!is_object($searchParams)) {
if (!empty($params['PaymentDate'] && !empty($params['ChequePostedDate'])) {
return $dataList->filter('PaymentDate:WithinRange', [$params['PaymentDate'], $params['ChequePostedDate']]);
}
}
return $dataList;
}
i solved it..
simply remove $filters
$filters = array(
// 'PaymentDate' => new PartialMatchFilter('PaymentDate'),
//'ChequePostedDate' => new PartialMatchFilter('ChequePostedDate'),
);
then it works

Laravel4: WhereHas Eloquent Issue (nested). callback function error

I tried doing a search function where the only field would be an <input type='text' /> it'll be stripped into an array() then passed to a whereLoop.
static function generateSearch($fields, $queryString)
{
return function($query) use($queryString, $fields)
{
foreach($fields as $field) {
$query = $query->orWhere($field, 'like', $queryString);
}
$query = $query->whereHas('category', function($_query) use ($queryString)
{
$_query->where('name','like',$queryString);
});
};
}
public static function search($query)
{
$searchBits = explode(' ', $query);
$query = Lead::with(array('user', 'category'));
$ctr = 0;
if(Category::whereIn('name', $searchBits)->count() != 0) {
$query = $query->whereHas('category', function($query) use ($searchBits)
{
$ctr = 0;
foreach($searchBits as $bit) {
$bit = "%".$bit."%";
$callback = "orWhere";
$queryFunc = Lead::generateSearch(array('name'), $bit);
if($ctr == 0) {
$callback = "where";
}
$query = $query->$callback($queryFunc);
}
});
}else {
foreach($searchBits as $bit) {
$bit = "%".$bit."%";
$callback = "orWhere";
$queryFunction = Lead::generateSearch(array('name', 'website', 'name', 'email'), $bit);
if($ctr == 0) {
$callback = "where";
}
$query = $query->$callback($queryFunction);
$ctr++;
}
}
$query = $query->orderBy('id','desc');
return $query;
}
Category only has ONE row as of the moment: its - "hot"
if i type in any keyword, it'll directly go to generateSearch()
but if i type in "hot", it'll send an error
Call to undefined method
Illuminate\Database\Query\Builder::category()
does anybody know what's up?
found the error. after looking deep within the callstack. i should not have added the
$query = $query->whereHas('category', function($_query) use ($queryString)
{
$_query->where('name','like',$queryString);
});
inside the generateSearch() or i should create another function for it. its being called by category callback as well.