I use jenssegers/laravel-mongodb. I make scope
public function scopeWhereFullText($query, $search)
{
return $query->whereRaw(['$text' => ['$search' => $search]],['score'=>['$meta'=>'textScore']]);
}
How I can order By score field like in MongoDB js example:
db.products.find({$text:{$search:"SomeText"}},{score:{$meta:'textScore'}}).sort({score:{$meta:'textScore'}})
What is the solution without crutch:
public function scopeWhereFullText($query, $search)
{
$query->getQuery()->projections = ['score'=>['$meta'=>'textScore']];
return $query->whereRaw(['$text' => ['$search' => $search]]);
}
and in result
$products = Product::whereFullText($request->get('q',''))
->orderBy('score',['$meta'=>'textScore'])->get();
$max = $products->max('score');
$min = $products->min('score');
$products = $products->filter(function($item) use($max,$min){
return $item->score > ($max+$min)/2;
});
Use
$results = DB::connection()->collection('_User')->whereRaw(['$text' => ['$search' => 'SEARCH QUERY']])->project(['score'=>['$meta'=>'textScore']])->orderBy('score', ['$meta' => "textScore"])->limit(10)->get();
Related
I have a problem in my custom registration controller; the redirecTo() is not working. After registration which is completely successful (in terms of database) I get a blank page and the URL never changes.
Here is the code of my Controller:
PS : I also used the method redirectPath() which also did not work.
<?php
namespace App\Http\Controllers\Auth\Login;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Auth\RegisterController as DefaultRegisterController;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\{Models\Medcine, Specialite ,SpecialiteMedcine};
use App\Http\Controllers\Controller;
class RegisterMedcineController extends DefaultRegisterController
protected $redirectTo = '/medcine/home';//This 1 is not working
public function redirectTo()//nd also this method is not working
{
dd(['Heelllooooooooo']);//shows nothing -_- that means that the system never caull this cursed method
return '/medcine/home';
}
public function showRegisterationForm()
{
return view('auth.register.medcine' , [
'Specialite' => Specialite::all()
]);
}
public function register(Request $request)
{
// dd($request);
$this->validate($request, [
'inp' => 'bail|required|between:6,20',
'password' => 'bail|required|between:8,255',
'nom' => 'bail|required|max:255',
'prenom' => 'bail|required|max:255',
'dateNaissance' => 'bail|required|date',
'tel' => 'bail|required|digits_between:10,20',
]);
$medcine = new Medcine();
// $specialite = new Specialite();
$specialiteMedcine = new SpecialiteMedcine();
$medcine->inp = $request->input('inp');
$value = $request->input('password');
bcrypt($value);
$medcine->password = bcrypt($value);
$medcine->email = $request->input('email');
$medcine->nom = $request->input('nom');
$medcine->prenom = $request->input('prenom');
$medcine->dateNaissance = $request->input('dateNaissance');
$medcine->lieuNaissance = $request->input('lieuNaissance');
$medcine->tel = $request->input('tel');
$medcine->genre = $request->input('genre');
$medcine->adress = $request->input('adress');
$specialiteMedcine->specialite_id = $request->input('Specialite');
$medcine->save();
$specialiteMedcine->medcine_id = $medcine->id;
$specialiteMedcine->save();
}
}
You can simply write your redirect code at the end of the Register method. Means:
public function register(Request $request)
{
$this->validate($request, [
'inp' => 'bail|required|between:6,20',
'password' => 'bail|required|between:8,255',
'nom' => 'bail|required|max:255',
'prenom' => 'bail|required|max:255',
'dateNaissance' => 'bail|required|date',
'tel' => 'bail|required|digits_between:10,20',
]);
$medcine = new Medcine();
// $specialite = new Specialite();
$specialiteMedcine = new SpecialiteMedcine();
$medcine->inp = $request->input('inp');
$value = $request->input('password');
bcrypt($value);
$medcine->password = bcrypt($value);
$medcine->email = $request->input('email');
$medcine->nom = $request->input('nom');
$medcine->prenom = $request->input('prenom');
$medcine->dateNaissance = $request->input('dateNaissance');
$medcine->lieuNaissance = $request->input('lieuNaissance');
$medcine->tel = $request->input('tel');
$medcine->genre = $request->input('genre');
$medcine->adress = $request->input('adress');
$specialiteMedcine->specialite_id = $request->input('Specialite');
$medcine->save();
$specialiteMedcine->medcine_id = $medcine->id;
$specialiteMedcine->save();
return redirect(route('your-route-name'));
}
In last line:
return redirect(route('your-route-name'));
I have a SQL query that return the result to List
public class WebTrafficStat
{
public string Group { get; set; }
public string Stat { get; set; }
public string Total { get; set; }
public bool? IsSubTotal { get; set; }
}
The result must be displayed as HTML Pivot table with either results grouped by "Stat" or "Group" field.
SQL result:
Desired result as HTML
I did the functions that does this PHP but now the project must be written in MVC Core
This is my PHP functions that I used currently
I grouped the array from SQL call results here:
function array_group_by(array $arr, $gElement, $gkey) {
$refined = $arr;
$result = array();
foreach ($arr[$gElement] as $data) {
$id = $data[$gkey];
if ( isset($data[$gkey]) && !empty($data[$gkey]) ) {
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
}
if ( !empty($result) ) {
$refined[$gElement] = array();
foreach($result as $key=>$value) {
$refined[$gElement][] = array('name' => $key, 'childs' => $value);
}
$refined['grouped'] = 1;
}
return $refined;
}
And second function is
function grouped_array_to_html ($grouped, $groupField ){
$tableRows = array();
$columns = array();
$Row_Data = array();
if ( $grouped['grouped'] == 1 ){ // grouping found
$columns[] = 'Group';
// table columns/headers
foreach ($grouped['rows'] as $row) {
foreach ($row['childs'] as $child) {
if ( !in_array($child[$groupField], $columns ) ){
$columns[] = $child[$groupField];
}
}
}
//table rows
foreach ($grouped['rows'] as $a => $row) {
$tableRows[$a][] = $row['name'];
foreach ($row['childs'] as $c => $child) {
foreach ($columns as $x => $col){
if ( $col == $child[$groupField] )
{
$tableRows[$a][$x] = $child['total'];
break;
}
}
}
}
//Output Finale
foreach ( $tableRows as $b => $tr )
{
foreach ($columns as $c => $col) {
if ( !isset($tableRows[$b][$c]) )
$Row_Data[$b][$c] = '-';
else
$Row_Data[$b][$c] = $tableRows[$b][$c];
}
}
} else { // no grouping
foreach ($grouped['rows'] as $row) {
$Row_Data[] = $row;
}
}
$htmlOut = array(
'theaders' => $columns,
'trows' => $Row_Data
);
$grouped['rows']['html'] = $htmlOut;
return $grouped;
}
And I call PHP like this ... this gives me HTML table header rows and Body rows
In this case, I tell it to group by "Stat" column
$result = grouped_array_to_html( array_group_by($response, 'rows', 'group'), 'stat' );
So please how can I achieve same result using EF Core or Linq
I ended up approaching it like this:
if ((Model.WebReport != null) && Model.WebReport.Rows.Any())
{
var columns = Model.WebReport.Rows
.Select(c => (Model.GroupBy.Equals("Group") ? c.Stat : c.Group))
.Distinct()
.ToList();
columns.Insert(0, "Group");
var reportStat = Model.WebReport.Rows
.GroupBy(g => (Model.GroupBy.Equals("Group") ? g.Group : g.Stat))
.Select(x => new
{
Group = x.Key,
Stats = x.ToDictionary(y => (Model.GroupBy.Equals("Group") ? y.Stat : y.Group), y => y.Total)
});
Model.Columns = columns;
Model.ReportStats = reportStat.ToList();
}
How can i use or condition in yii2 advanced template with mongoDB:
what i want:
$sql = "SELECT * FROM admin WHERE (username = '$username' OR email = '$username');
How can i put this condition in following function:
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}
I have solved like this:
public static function findByUsername($username)
{
$con = array('$or' => array(array('username' => $username),array('email' => $username)));
return static::findOne($con);
}
I have here many-to-many table, i need to get just inserted id - BlogId. lastInsertId() is NULL result. Any ideas?
$table = new Blog_Model_Blog_Table();
$relTable = new Blog_Model_Relation_Table();
$Object = $table->createRow();
$form = new Blog_Form_Blog_Add($Object);
if ($this->getRequest()->isPost() and $form->isValid($_POST)) {
Blog_Model_Blog_Manager::add($Object);
$blogId = $table->getAdapter()->lastInsertId();
foreach ($_POST['category_id'] as $value) {
$relTable->insert(array('id' => $blogId, 'category_id' => $value));
}
Blog_Model_Blog_Manager:
class Blog_Model_Blog_Manager
{
static function add(Blog_Model_Blog_Item &$Object)
{
$data = array(
'time_add' => time(),
'time_edit' => time(),
'url_keyword' => Ap_Filter_Translit::asURLSegment($Object->name)
);
$Object->setFromArray($data)
->save();
}
I make it with mySql function LAST_INSERT_ID():
$blogId = $table->fetchRow($table->select()->from($table)->columns('LAST_INSERT_ID() as idi'));
I've got a problem with insert and update queries in Zend (Select is ok).
Definition of table:
class Application_Model_DbTable_Kpr1Data extends Zend_Db_Table_Abstract
{
protected $_name = 'kpr_kpr1_data';
}
Here is my data mapper (model)
class Application_Model_Kpr1DataMapper
{
protected $_dbTable;
public function setdbTable($dbTable) {
if(is_string($dbTable)){
$dbTable = new $dbTable();
}
if(!$dbTable instanceof Zend_Db_Table_Abstract ){
throw new Exception ('Invalid table data gateway provided.');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getdbTable() {
if (null === $this->_dbTable){
$this->setdbTable('Application_Model_DbTable_Kpr1Data');
}
return $this->_dbTable;
}
public function save(Application_Model_Kpr1Data $kpr1data){
$data = array('id' => (int) $kpr1data->getId(),
'kpr1_plaza_id' => (int) $kpr1data->getPlaza(),
'kpr1_data' => new Zend_db_Expr("STR_TO_DATE('".$kpr1data->getDate()."', '%Y-%m-%d')"),
'kpr1_money_delivered' => (float) $kpr1data->getDelivered(),
'kpr1_money_transactions' => (float) $kpr1data->getTransactions(),
'kpr1_created' => new Zend_Db_Expr('CURDATE()')
);
$id = (int) $kpr1data->getId();
$table = $this->getdbTable();
if (is_null($id) && $id != 0) {
unset($data['id']);
$table->insert($data);
} else {
$table->update($data, array('id => ?', $id));
}
}
The last one is save function that should insert and update the data!
And this save is called from save action:
public function saveAction()
{
$plazaid = (int) $this->getRequest()->getParam('plaza');
$date = (string) $this->getRequest()->getParam('date');
$delivered = (string) $this->getRequest()->getParam('delivered');
$transactions = (string) $this->getRequest()->getParam('transactions');
$kpr1data = new Application_Model_Kpr1Data();
if ($plazaid && $date) {
$kpr1datamapper = new Application_Model_Kpr1DataMapper();
if($kpr1datamapper->findDatePlaza($date, $plazaid, $kpr1data)){
$kpr1data->setDelivered($delivered)
->setTransactions($transactions);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
} else {
$kpr1data->setDate($date);
$kpr1data->setDelivered($delivered);
$kpr1data->setTransactions($transactions);
$kpr1data->setPlaza($plazaid);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
}
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array(
//"success"=>"false",
"errorMsg"=>"Saving error"
));
} else {
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array(
//"success"=>"false",
"errorMsg"=>"Saving error"
));
}
return true;
}
Save action is called via JS, but even called directly through webbrowser it fails.
Behaviour: Application is running, and when debugger runs into update/insert line:
if (is_null($id) && $id != 0) {
unset($data['id']);
$table->insert($data);
} else {
$table->update($data, array('id => ?', $id));
}
it's redirecting to ErrorController.
I've check that:
1. firePHP is not showing this statements
2. MySQL database doesn't log this statement (I've checked via general_log feature).
I'm stucked. Help me please.
edit
$data=
array(6) (
[id] => (int) 0
[kpr1_plaza_id] => (int) 116
[kpr1_data] => Zend_Db_Expr object {
_expression => (string) STR_TO_DATE('2013-03-01', '%Y-%m-%d')
}
[kpr1_money_delivered] => (float) 120
[kpr1_money_transactions] => (float) 122
[kpr1_created] => Zend_Db_Expr object...
$kpr1data=
Application_Model_Kpr1Data object {
_plaza => (string) 116
_date => (string) 2013-03-01
_delivered => (string) 120.00
_transactions => (string) 122.00
_created => null
_id => null
_plazaname => null
}
This one should do insert.
And next one update:
Application_Model_Kpr1Data object {
_plaza => (string) 117
_date => (string) 2013-03-01
_delivered => (string) 120.00
_transactions => (string) 122.00
_created => (string) 2013-03-06 12:42:13
_id => (string) 79
_plazaname => (string) SPO Kraj...
in your saveAction() $this->view->result gets overwritten after if/else statement since your function does not return anything after (initially) setting $this->view->result.
Furthermore setting the first Saving error seems to be needless.
Try this:
public function saveAction()
{
$plazaid = (int) $this->getRequest()->getParam('plaza');
$date = (string) $this->getRequest()->getParam('date');
$delivered = (string) $this->getRequest()->getParam('delivered');
$transactions = (string) $this->getRequest()->getParam('transactions');
$kpr1data = new Application_Model_Kpr1Data();
if ($plazaid && $date) {
$kpr1datamapper = new Application_Model_Kpr1DataMapper();
if($kpr1datamapper->findDatePlaza($date, $plazaid, $kpr1data)){
$kpr1data->setDelivered($delivered)
->setTransactions($transactions);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
} else {
$kpr1data->setDate($date);
$kpr1data->setDelivered($delivered);
$kpr1data->setTransactions($transactions);
$kpr1data->setPlaza($plazaid);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
}
} else {
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array(
//"success"=>"false",
"errorMsg"=>"Saving error"
));
}
return true;
}
EDIT:
Try this as your save action:
public function save(Application_Model_Kpr1Data $kpr1data){
$table = $this->getdbTable();
if ($id == $kpr1data->getId()) {
$data = array('id' => (int) $id,
'kpr1_plaza_id' => (int) $kpr1data->getPlaza(),
'kpr1_data' => new Zend_Db_Expr("STR_TO_DATE('".$kpr1data->getDate()."', '%Y-%m-%d')"),
'kpr1_money_delivered' => (float) $kpr1data->getDelivered(),
'kpr1_money_transactions' => (float) $kpr1data->getTransactions(),
'kpr1_created' => new Zend_Db_Expr('CURDATE()')
);
$table->update($data, array('id => ?', $id));
} else {
[...]
$table->insert($data);
}
}