How do I update all rows in a table (all IDs) at once, with a database query in Laravel? My current controller code is as follows:
public function updateSchedule(Request $request, $id)
{
$timein = $request->input('timeIn');
$timeout = $request->input('timeOut');
DB::table('schedules')
->where('id', 1)
->update(['time_in' => $timein, 'time_out' => $timeout]);
}
To update the whole table (the WHOLE TABLE), you would do the following (removing the condition that you only want to update matches where id = 1):
public function updateSchedule(Request $request, $id)
{
$timein = $request->input('timeIn');
$timeout = $request->input('timeOut');
DB::table('schedules')
->update(['time_in' => $timein, 'time_out' => $timeout]);
}
If you want to see something afterwards, you either need to return that value, or a view, or a redirect to the prior page.
For example, the following (although it's not good practice to use back() as you don't know where they came from. It's better to go to a specific route / url).
public function updateSchedule(Request $request, $id)
{
$timein = $request->input('timeIn');
$timeout = $request->input('timeOut');
DB::table('schedules')
->update(['time_in' => $timein, 'time_out' => $timeout]);
return back();
}
Related
I have multiple campaigns, that can be assigned to multiple users. Basically, they have belongsToMany relation both ways.
I would like to print out the results on the page, that only belongs to that specific user, based on the pivot table.
Models:
User model:
public function campaign()
{
return $this->belongsToMany(Campaign::class, 'campaign_user');
}
Campaign model:
public function users()
{
return $this->belongsToMany(Gift::class, 'campaign_user');
}
Migration of pivot table:
public function up()
{
Schema::create('campaign_user', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->onDelete('cascade');;
$table->foreignId('campaign_id')->constrained()->onDelete('cascade');
});
}
Incorrect Controller:
public function index(Request $request)
{
$data = Campaign::withCount('gifts');
$data->where('user_id', $request->user()->id)->get();
return view('subscribes.index', ['data' => $data]);
}
Basically, all I need, is to return specific campaigns, that the client has subscribed only, based on the pivot table/user id. Thus, editing this Controller.
I still face lots of issues with Eloquent models and pivot tables, and I would be very thankful, for any assistance in regards to it.
This will make more sense if you rename the relationship campaign() to it's plural campaigns() on your User model.
Once you have the relationships set up, you can access campaigns for the user straight from the user object.
$user = $request->user();
$data = $user->campaigns;
Note also, if your user is authenticated, you can access them easily like:
$user = auth()->user();
So your index method in your controller would be
public function index(Request $request)
{
$user = $request->user();
$data = $user->campaigns;
return view('subscribes.index', ['data' => $data]);
}
I'm trying to learn cakephp 3 and the ORM functions, wicht is great so far. But know I'm comming to a point on wich I'm not certain how I can aproach it in the best way, so I was hoping that somebody can tell what is the best way.
I'm using the query builder to load one or more products. In the data that's loaded I have one field called price. This is the main price of the product, but there can be an optional discount for an user. I know wich user is logged in to the system so I have an variabele witch contains his discount, for example 1.20 (=20%).
After the query has been fired I could do an foreach and recalculate the price before sending is to the view, but because of the query builder function I suspect that I can do it there before I fired the query.
Below an example where an search is done on input name. The field price is now standard, but should be recalculated with the discount.This could be an foreacht example:
$price = round((($price/$User->discount)-$shipping),2);
SearchController:
public function search()
{
if ($this->request->is('post')) {
//$this->request->data);
$options = array();
$options['query'] = $this->request->data['Search']['query'];
$products = TableRegistry::get('Products');
$query = $products->find('search', $options);
$number = $query->count();
$products = $query->All();
$this->set(compact('products'));
$this->set('number_of_results',$number);
}
The ProductsTable:
public function findSearch(Query $query, array $options)
{
$query
->where([
'name LIKE' => '%'.$options['query'].'%',
"active" => 1
])
->contain(['ProductsImages'])
->select(['id','name','price','delivery_time','ProductsImages.image_url'])
;
return $query;
}
Is there an way to implement this recalculation in the query builder? I tried to find some info on the web but there isn't much information yet about the ORM options. I was thinking about maybe ->combine. Hopefully someone wants to put me in the right direction.
Thanks in forward.
Changed the controller function to:
public function search()
{
if ($this->request->is('post')) {
$options = array();
$options['query'] = $this->request->data['Search']['query'];
$discount = 2;
$products = TableRegistry::get('Products');
$query = $products
->find('search', $options);
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $products) {
return $products->map(function ($row) {
$row['price'] = ($row['price'] + 10);
return $row;
});
});
$number = $query->count();
$products = $query->All();
$this->set(compact('products'));
$this->set('number_of_results',$number);
}
}
I'm new to Yii and I have a table 'Student' with fields like 'stdStudentId', 'stdName', etc.
I'm making API, so this data should be returned in JSON. Now, because I want field names in JSON to just be like 'id', 'name', and I don't want all fields returned, i made a method in the model:
public function APIfindByPk($id){
$student = $this->findByPk($id);
return array(
'id'=>$student->stdStudentId,
'name'=>$student->stdName,
'school'=>$student->stdSchool
);
}
The problem is, stdSchool is a relation and in this situation, $student->stdSchool returns array with fields like schSchoolId, schName, etc. I don't want fields to be named like that in JSON, and also I don't want all the fields from School returned and I would like to add some fields of my own. Is there a way to do this in Yii, or I'll have to do it manually by writing methods like this?
I have been looking for the same thing. There is a great php lib named Fractal letting you achieve it: http://fractal.thephpleague.com/
To explain briefly the lib, for each of your models you create a Transformer that will be doing the mapping between your model attributes and the ones that need to be exposed using the api.
class BookTransformer extends Fractal\TransformerAbstract
{
public function transform(Book $book)
{
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
];
}
}
In the transformer you can also set the relation that this model have :
class BookTransformer extends TransformerAbstract
{
/**
* List of resources relations that can be used
*
* #var array
*/
protected $availableEmbeds = [
'author'
];
/**
* Turn this item object into a generic array
*
* #return array
*/
public function transform(Book $book)
{
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
];
}
/**
* Here we are embeding the author of the book
* using it's own transformer
*/
public function embedAuthor(Book $book)
{
$author = $book->author;
return $this->item($author, new AuthorTransformer);
}
}
So at the end you will call
$fractal = new Fractal\Manager();
$resource = new Fractal\Resource\Collection($books, new BookTransformer);
$json = $fractal->createData($resource)->toJson();
It's not easy to describe all the potential of fractal in one answer but you really should give it a try.
I'm using it along with Yii so if you have some question don't hesitate!
Since you are getting the values from the database using Yii active record, ask the database to use column aliases.
Normal SQL would be something like the following :
SELECT id AS Student_Number, name AS Student_Name, school AS School_Attending FROM student;
In Yii, you can apply Criteria to the findByPK() function. See here for reference : http://www.yiiframework.com/doc/api/1.1/CActiveRecord#findByPk-detail
$criteria = new CDbCriteria();
$criteria->select = 'id AS Student_Number';
$student = Student::model()->findByPk($id, $criteria);
Note that in order to use a column alias like that, you will have to define a virtual attribute Student_Number in your Student{} model.
Override the populateRecord() function of ActiveRecord can achieve this!
My DishType has 5 properties and override the populateRecord function Yii would invoke this when records fetched from db.
My code is here!
class DishType extends ActiveRecord
{
public $id;
public $name;
public $sort;
public $createTime;
public $updateTime;
public static function populateRecord($record, $row)
{
$pattern = ['id' => 'id', 'name' => 'name', 'sort' => 'sort', 'created_at' => 'createTime', 'updated_at' => 'updateTime'];
$columns = static::getTableSchema()->columns;
foreach ($row as $name => $value) {
$propertyName = $pattern[$name];
if (isset($pattern[$name]) && isset($columns[$name])) {
$record[$propertyName] = $columns[$name]->phpTypecast($value);
}
}
parent::populateRecord($record, $row);
}
}
I am trying to query a products table, and want it to return a collection if a relation exists.
Iteration 1 below queries all rows in the products table, and lazy loads the metals table if $name matches. This is wrong.
My Route:
Route::group(array('prefix' => '{api}/v1'), function()
{
Route::controller('products', 'Api\V1\ProductController');
});
My Controller:
public function getFilter($metal = null) {
$products = $this->product;
if ($metal) {
$products->with('metal', function($query, $metal) {
$query->where('name', $metal);
});
}
return Response::api($products->get());
}
I want only $products to display if metal.name = $metal. e.g. something like:
$this->products->where('metal.name', $metal)->get;
Solution using part of Glad To Help's answer:
This provides an alternative approach 2, without the need for joins.
http://paste.laravel.com/WC4
Unfortunately you cannot do this with one swipe in Eloquent yet.
BUT, there is a way by using the inverse relation, like this:
public function getFilter($metal = null)
{
// filter the metals first
$metals = Metal::with('products')->where('name', '=' , $metal)->get();
$products = array();
foreach($metals as $metal)
{
// collect the products from the filtered metals
$products = array_merge($products, $metal->products->toArray() );
}
return $products;
}
If this is not elegant solution for you, you will either have to use Fluent to construct the query and join the products x metals table manually or pre-join them by overriding the newQuery() method.
1) alternative approach one.
public function getFilter($metal = null) {
return DB::table('products')->join('metal', 'products.id', '=' , 'metal.product_id')
->where('metal.name', $name)
->select(array('products.*'));
}
2) alternative approach two
class Product extends Eloquent{
public function newQuery($excludeDeleted = true){
return parent::newQuery()->join('metal','id','=','metal.product_id');
}
}
I am working with options, to add some additional info like image. and I saved this data to my own table with option_type_id and option_id. now on frontend I would like to join my own table data to default options. so these options come with image info.
$_option->getValues()
this function returns option data, now I have to reach the implementation of this function where it generate the query so I could add join to retrieve my own data with.
I dont see a clean way to do this.
Here is a dirty way:
RewriteMage_Catalog_Model_Resource_Product_Option and add this function below.
Modify it with you join. however the join to you table would then be done for every product option. You will need to check for somekind of a flag and only add your join if this flag is set.
protected function _getLoadSelect($field, $value, $object)
{
$select = parent::_getLoadSelect($field, $value, $object);
if("do your check here"){
$select->join('your table')
}
return $select;
}
Here is what i got success from.
i overridden the resource collection of product
class MYC_COPSwatch_Model_Resource_Product_Option_Collection extends Mage_Catalog_Model_Resource_Product_Option_Collection{
public function addValuesToResult($storeId = null)
{
if ($storeId === null) {
$storeId = Mage::app()->getStore()->getId();
}
$optionIds = array();
foreach ($this as $option) {
$optionIds[] = $option->getId();
}
if (!empty($optionIds)) {
/** #var $values Mage_Catalog_Model_Option_Value_Collection */
$values = Mage::getModel('catalog/product_option_value')
->getCollection()
->addTitleToResult($storeId)
->addPriceToResult($storeId)
->addSwatchToResult($storeId) //USED Join in this function
->setOrder('sort_order', self::SORT_ORDER_ASC)
->setOrder('title', self::SORT_ORDER_ASC);
foreach ($values as $value) {
$optionId = $value->getOptionId();
if($this->getItemById($optionId)) {
$this->getItemById($optionId)->addValue($value);
$value->setOption($this->getItemById($optionId));
}
}
}
return $this;
}
might be save time for someone.