I'm trying to update multiple models with a directive, but the current #update directive does not support multiple ids. I would basically want the #delete directive (where you can use a list of ids). To update multiple models. I'm guessing I could create a custom directive, but it's alot of code there that I can't wrap my head around. I've tried to read the docs to understand how to create a custom directive, but I can't get it to work.
So the DeleteDirective.php got this:
/**
* Bring a model in or out of existence.
*
* #param \Illuminate\Database\Eloquent\Model $model
* #return void
*/
protected function modifyExistence(Model $model): void
{
$model->delete();
}
And I would basically want this (for multiple ids):
/**
* Update a model to read true
*
* #param \Illuminate\Database\Eloquent\Model $model
* #return void
*/
protected function updateRead(Model $model): void
{
$model->update(['read' => true]);
}
By defining a mutation query like this:
type Mutation {
updatePostsToRead(id: [ID!]!): [Post!]! #updateRead
}
And doing a query like this:
{
mutation {
updatePostsToRead(id: [6,8]) {
id
amount
}
}
}
Does anyone know how I would go by doing this? Or can point me in the right direction?
Found a way to do it without creating a custom directive. Just made a custom mutation with php artisan lighthouse:mutation updatePostsToRead.
updatePostsToRead.php:
class updatePostsToRead
{
/**
* Return a value for the field.
*
* #param null $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
* #param mixed[] $args The arguments that were passed into the field.
* #param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context Arbitrary data that is shared between all fields of a single query.
* #param \GraphQL\Type\Definition\ResolveInfo $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
* #return mixed
*/
public function __invoke(
$rootValue,
array $args,
GraphQLContext $context,
ResolveInfo $resolveInfo
) {
// TODO implement the resolver
\DB::table('posts')
->whereIn('id', $args["ids"])
->update(['read' => true]);
$posts = Post::whereIn('id', $args["ids"])->get();
return $posts;
}
}
Schema:
type Mutation {
updatePostsToRead(ids: [ID]): [Post]
}
Query on client:
mutation{
updatePostsToRead(ids: [2,6,8]) {
id
description
read
}
}
Related
I have PostController, here is its method store().
public function store(Request $request)
{
$this->handleUploadedImage(
$request->file('upload'),
$request->input('CKEditorFuncNum')
);
$post = Post::create([
'content' => request('content'),
'is_published' => request('is_published'),
'slug' => Carbon::now()->format('Y-m-d-His'),
'title' => $this->firstSentence(request('content')),
'template' => $this->randomTemplate(request('template')),
]);
$post->tag(explode(',', $request->tags));
return redirect()->route('posts');
}
Method handleUploadedImage() now stored in PostController itself. But I'm going to use it in other controllers. Where should I move it? Not in Request class, because it's not about validation. Not in Models/Post, because it's not only for Post model. And it's not so global function for Service Provider class.
Methods firstSentence() and randomTemplate() are stored in that controller too. They will only be used in it. Maybe I should move them in Models/Post? In that way, how exactly call them in method store() (more specifically, in method create())?
I read the theory, and I understand (hopefully) the Concept of Thin Controllers and Fat Models, but I need some practical concrete advice with this example. Could you please suggest, where to move and how to call these methods?
First, a note: I don't work with Laravel, so I'll show you a general solution, pertinent to all frameworks.
Indeed, the controllers should always be kept thin. But this should be appliable to the model layer as well. Both goals are achievable by moving application-specific logic into application services (so, not into the model layer, making the models fat!). They are the components of the so-called service layer. Read this as well.
In your case, it seems that you can elegantly push the handling logic for uploaded images into a service, like App\Service\Http\Upload\ImageHandler, for example, containing a handle method. The names of the class and method could be chosen better, though, dependent on the exact class responsibility.
The logic for creating and storing a post would go into another application service: App\Service\Post, for example. In principle, this service would perform the following tasks:
Create an entity - Domain\Model\Post\Post, for example - and set its properties (title, content, is_published, template, etc) based on the user input. This could be done in a method App\Service\Post::createPost, for example.
Store the entity in the database, as a database record. This could be done in a method App\Service\Post::storePost, for example.
Other tasks...
In regard of the first task, two methods of the App\Service\Post service could be useful:
generatePostTitle, encapsulating the logic of extracting the first sentence from the user-provided "content", in order to set the title of the post entity from it;
generatePostTemplate, containing the logic described by you in the comment in regard of randomTemplate().
In regard of the second task, personally, I would store the entity in the database by using a specific data mapper - to directly communicate with the database API - and a specific repository on top of it - as abstraction of a collection of post objects.
Service:
<?php
namespace App\Service;
use Carbon;
use Domain\Model\Post\Post;
use Domain\Model\Post\PostCollection;
/**
* Post service.
*/
class Post {
/**
* Post collection.
*
* #var PostCollection
*/
private $postCollection;
/**
* #param PostCollection $postCollection Post collection.
*/
public function __construct(PostCollection $postCollection) {
$this->postCollection = $postCollection;
}
/**
* Create a post.
*
* #param string $content Post content.
* #param string $template The template used for the post.
* #param bool $isPublished (optional) Indicate if the post is published.
* #return Post Post.
*/
public function createPost(
string $content,
string $template,
bool $isPublished
/* , ... */
) {
$title = $this->generatePostTitle($content);
$slug = $this->generatePostSlug();
$template = $this->generatePostTemplate($template);
$post = new Post();
$post
->setTitle($title)
->setContent($content)
->setIsPublished($isPublished ? 1 : 0)
->setSlug($slug)
->setTemplate($template)
;
return $post;
}
/**
* Store a post.
*
* #param Post $post Post.
* #return Post Post.
*/
public function storePost(Post $post) {
return $this->postCollection->storePost($post);
}
/**
* Generate the title of a post by extracting
* a certain part from the given post content.
*
* #return string Generated post title.
*/
private function generatePostTitle(string $content) {
return substr($content, 0, 300) . '...';
}
/**
* Generate the slug of a post.
*
* #return string Generated slug.
*/
private function generatePostSlug() {
return Carbon::now()->format('Y-m-d-His');
}
/**
* Generate the template assignable to
* a post based on the given template.
*
* #return string Generated post template.
*/
private function generatePostTemplate(string $template) {
return 'the-generated-template';
}
}
Repository interface:
<?php
namespace Domain\Model\Post;
use Domain\Model\Post\Post;
/**
* Post collection interface.
*/
interface PostCollection {
/**
* Store a post.
*
* #param Post $post Post.
* #return Post Post.
*/
public function storePost(Post $post);
/**
* Find a post by id.
*
* #param int $id Post id.
* #return Post|null Post.
*/
public function findPostById(int $id);
/**
* Find all posts.
*
* #return Post[] Post list.
*/
public function findAllPosts();
/**
* Check if the given post exists.
*
* #param Post $post Post.
* #return bool True if post exists, false otherwise.
*/
public function postExists(Post $post);
}
Repository implementation:
<?php
namespace Domain\Infrastructure\Repository\Post;
use Domain\Model\Post\Post;
use Domain\Infrastructure\Mapper\Post\PostMapper;
use Domain\Model\Post\PostCollection as PostCollectionInterface;
/**
* Post collection.
*/
class PostCollection implements PostCollectionInterface {
/**
* Posts list.
*
* #var Post[]
*/
private $posts;
/**
* Post mapper.
*
* #var PostMapper
*/
private $postMapper;
/**
* #param PostMapper $postMapper Post mapper.
*/
public function __construct(PostMapper $postMapper) {
$this->postMapper = $postMapper;
}
/**
* Store a post.
*
* #param Post $post Post.
* #return Post Post.
*/
public function storePost(Post $post) {
$savedPost = $this->postMapper->savePost($post);
$this->posts[$savedPost->getId()] = $savedPost;
return $savedPost;
}
/**
* Find a post by id.
*
* #param int $id Post id.
* #return Post|null Post.
*/
public function findPostById(int $id) {
//...
}
/**
* Find all posts.
*
* #return Post[] Post list.
*/
public function findAllPosts() {
//...
}
/**
* Check if the given post exists.
*
* #param Post $post Post.
* #return bool True if post exists, false otherwise.
*/
public function postExists(Post $post) {
//...
}
}
Data mapper interface:
<?php
namespace Domain\Infrastructure\Mapper\Post;
use Domain\Model\Post\Post;
/**
* Post mapper.
*/
interface PostMapper {
/**
* Save a post.
*
* #param Post $post Post.
* #return Post Post entity with id automatically assigned upon persisting.
*/
public function savePost(Post $post);
/**
* Fetch a post by id.
*
* #param int $id Post id.
* #return Post|null Post.
*/
public function fetchPostById(int $id);
/**
* Fetch all posts.
*
* #return Post[] Post list.
*/
public function fetchAllPosts();
/**
* Check if a post exists.
*
* #param Post $post Post.
* #return bool True if the post exists, false otherwise.
*/
public function postExists(Post $post);
}
Data mapper PDO implementation:
<?php
namespace Domain\Infrastructure\Mapper\Post;
use PDO;
use Domain\Model\Post\Post;
use Domain\Infrastructure\Mapper\Post\PostMapper;
/**
* PDO post mapper.
*/
class PdoPostMapper implements PostMapper {
/**
* Database connection.
*
* #var PDO
*/
private $connection;
/**
* #param PDO $connection Database connection.
*/
public function __construct(PDO $connection) {
$this->connection = $connection;
}
/**
* Save a post.
*
* #param Post $post Post.
* #return Post Post entity with id automatically assigned upon persisting.
*/
public function savePost(Post $post) {
/*
* If $post->getId() is set, then call $this->updatePost()
* to update the existing post record in the database.
* Otherwise call $this->insertPost() to insert a new
* post record in the database.
*/
// ...
}
/**
* Fetch a post by id.
*
* #param int $id Post id.
* #return Post|null Post.
*/
public function fetchPostById(int $id) {
//...
}
/**
* Fetch all posts.
*
* #return Post[] Post list.
*/
public function fetchAllPosts() {
//...
}
/**
* Check if a post exists.
*
* #param Post $post Post.
* #return bool True if the post exists, false otherwise.
*/
public function postExists(Post $post) {
//...
}
/**
* Update an existing post.
*
* #param Post $post Post.
* #return Post Post entity with the same id upon updating.
*/
private function updatePost(Post $post) {
// Persist using SQL and PDO statements...
}
/**
* Insert a post.
*
* #param Post $post Post.
* #return Post Post entity with id automatically assigned upon persisting.
*/
private function insertPost(Post $post) {
// Persist using SQL and PDO statements...
}
}
In the end, your controller would look something like bellow. By reading its code, its role becomes obvious: just to push the user input to the service layer. The use of a service layer provides the big advantage of reusability.
<?php
namespace App\Controller;
use App\Service\Post;
use App\Service\Http\Upload\ImageHandler;
class PostController {
private $imageHandler;
private $postService;
public function __construct(ImageHandler $imageHandler, Post $postService) {
$this->imageHandler = $imageHandler;
$this->postService = $postService;
}
public function storePost(Request $request) {
$this->imageHandler->handle(
$request->file('upload'),
$request->input('CKEditorFuncNum')
);
$post = $this->postService->createPost(
request('content'),
request('template'),
request('is_published')
/* , ... */
);
return redirect()->route('posts');
}
}
PS: Keep in mind, that the model layer MUST NOT know anything about where its data is coming from, nor about how the data passed to it was created. So, the model layer must not know anything about a browser, or a request, or a controller, or a view, or a response, or etc. It just receives primitive values, objects, or DTOs ("data transfer objects") as arguments - see repository and data mapper above, for example.
PS 2: Note that a lot of frameworks are talking about repositories, but, in fact, they are talking about data mappers. My suggestion is to follow Fowler's conventions in your mind and your code. So, create data mappers in order to directly access a persistence space (database, filesystem, etc). If your project becomes more complex, or if you just want to have collection-like abstractions, then you can add a new layer of abstraction on top of the mappers: the repositories.
Resources
Keynote: Architecture the Lost Years by Robert C. Martin
Sandro Mancuso : Crafted Design
Clean, high quality code...
And a good 4-parts series of Gervasio on sitepoint.com:
Building a Domain Model - An Introduction to Persistence Agnosticism
Building a Domain Model – Integrating Data Mappers
Handling Collections of Aggregate Roots – the Repository Pattern
An Introduction to Services
What i usually do
public function store(ValidationRequest $request)
{
$result = $this->dispatchNow($request->validated())
return redirect()->route('posts');
}
So, i create a job for handling those registration steps, and i can reuse that in another parts of my system.
Your firstSentence i would move to an helper called strings app\helpers\strings (and don't forget to update that in composer.json and you could use just firstSentence($var) in any part of your system
The randomTemplate would fit nicelly in a trait, but i don't know what this methods does.
I am trying to do something that seems to go out of the box with how laravel-nova works ...
I have a Batch model/ressource that is used by super admins. Those batch reeports belongs to sevral merchants. We decided to add a layer of connection to are portal and allow merchants to log in and see there data. So obviously, when the merchant visites the batch repport page, he needs to see only data related to it's own account.
So what we did was add the merchant id inside the batch page like this:
nova/resources/batch?mid=0123456789
The problem we then found out is that the get param is not send to the page it self but in a subpage called filter ... so we hacked it and found a way to retreive it like this:
preg_match('/mid\=([0-9]{10})/', $_SERVER['HTTP_REFERER'], $matches);
Now that we have the mid, all we need to do is add a where() to the model but it's not working.
Obviously, this appoach is not the right way ... so my question is not how to make this code work ... but how to approche this to make it so that merchants can only see his own stuff when visiting a controller.
All i really need to is add some sort of a where('external_mid', '=' $mid) and everything is good.
The full code looks like this right now:
<?php
namespace App\Nova;
use App\Nova\Resource;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\BelongsTo;
use App\Nova\Filters\StatementDate;
use Laravel\Nova\Http\Requests\NovaRequest;
class Batch extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
//
public static function query(){
preg_match('/mid\=([0-9]{10})/', $_SERVER['HTTP_REFERER'], $matches);
if (isset($matches['1'])&&$matches['1']!=''){
$model = \App\Batch::where('external_mid', '=', $matches['1']);
}else{
$model = \App\Batch::class;
}
return $model;
}
public static $model = $this->query();
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id','customer_name', 'external_mid', 'merchant_id', 'batch_reference', 'customer_batch_reference',
'batch_amt', 'settlement_date', 'fund_amt', 'payment_reference', 'payment_date'
];
/**
* Indicates if the resource should be globally searchable.
*
* #var bool
*/
public static $globallySearchable = false;
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->hideFromIndex(),
Text::make('Customer','customer_name'),
Text::make('MID','external_mid'),
Text::make('Batch Ref #','batch_reference'),
Text::make('Batch ID','customer_batch_reference'),
Text::make('Batch Date','settlement_date')->sortable(),
Currency::make('Batch Amount','batch_amt'),
Text::make('Funding Reference','payment_reference')->hideFromIndex(),
Text::make('Funding Date','payment_date')->hideFromIndex(),
Currency::make('Funding Amount','fund_amt')->hideFromIndex(),
// **Relationships**
HasMany::make('Transactions'),
BelongsTo::make('Merchant')->hideFromIndex(),
// ***
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [
];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
In Laravel Nova you can modify the result query of any Resource by adding the index Query method. This method allows you to use Eloquent to modify the results with any condition you define.
I understand you just need to maintain the $model property with the model with the default definition and modify the results in the indexQuery method:
...
public static $model = \App\Batch::class;
public static function indexQuery(NovaRequest $request, $query)
{
// Using the same logic of the example above. I recommend to use the $request variable to access data instead of the $_SERVER global variable.
preg_match('/mid\=([0-9]{10})/', $_SERVER['HTTP_REFERER'], $matches);
if (isset($matches['1'])&&$matches['1']!=''){
return $query->where('external_mid', '=', $matches['1']);
}else{
return $query;
}
}
...
About the use of the PHP Global Variable, I recommend you to use the laravel default request() to look into your URL. You can use something like this $request->mid to read the value from the mid value in the URL.
So I'm using the Laravel model event observerables to fire custom event logic, but they only accept the model as a single argument. What I'd like to do is call a custom event that I can also pass some extra arguments to that would in turn get passed to the Observer method. Something like this:
$this->fireModelEvent('applied', $user, $type);
And then in the Observer
/**
* Listen to the applied event.
*
* #param Item $item
* #param User $user
* #param string $type
* #return void
*/
public function applied(Item $item, $user, string $type) {
Event::fire(new Applied($video, $user, $type));
}
As you can see i'm interested in passing a user that performed this action, which is not the one that necessarily created the item. I don't think temporary model attributes are the answer because my additional event logic gets queued off as jobs to keep response time as low as possible. Anyone have any ideas on how I could extend Laravel to let me do this?
My theory would be to do a custom trait that overrides one or more functions in the base laravel model class that handles this logic. Thought I'd see if anyone else has needed to do this while I look into it.
Also here's the docs reference
I've accomplished this task by implementing some custom model functionality using a trait.
/**
* Stores event key data
*
* #var array
*/
public $eventData = [];
/**
* Fire the given event for the model.
*
* #param string $event
* #param bool $halt
* #param array $data
* #return mixed
*/
protected function fireModelEvent($event, $halt = true, array $data = []) {
$this->eventData[$event] = $data;
return parent::fireModelEvent($event, $halt);
}
/**
* Get the event data by event
*
* #param string $event
* #return array|NULL
*/
public function getEventData(string $event) {
if (array_key_exists($event, $this->eventData)) {
return $this->eventData[$event];
}
return NULL;
}
<?php
/**
* #link http://www.yiiframework.com/
* #copyright Copyright (c) 2008 Yii Software LLC
* #license http://www.yiiframework.com/license/
*/
namespace yii\data;
use Yii;
use yii\base\Component;
use yii\base\InvalidParamException;
/**
* BaseDataProvider provides a base class that implements the [[DataProviderInterface]].
*
* #property integer $count The number of data models in the current page. This property is read-only.
* #property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is
* uniquely identified by the corresponding key value in this array.
* #property array $models The list of data models in the current page.
* #property Pagination|boolean $pagination The pagination object. If this is false, it means the pagination
* is disabled. Note that the type of this property differs in getter and setter. See [[getPagination()]] and
* [[setPagination()]] for details.
* #property Sort|boolean $sort The sorting object. If this is false, it means the sorting is disabled. Note
* that the type of this property differs in getter and setter. See [[getSort()]] and [[setSort()]] for details.
* #property integer $totalCount Total number of possible data models.
*
* #author Qiang Xue <qiang.xue#gmail.com>
* #since 2.0
*/
abstract class BaseDataProvider extends Component implements DataProviderInterface
{
/**
* #var string an ID that uniquely identifies the data provider among all data providers.
* You should set this property if the same page contains two or more different data providers.
* Otherwise, the [[pagination]] and [[sort]] may not work properly.
*/
public $id;
private $_sort;
private $_pagination;
private $_keys;
private $_models;
private $_totalCount;
/**
* Prepares the data models that will be made available in the current page.
* #return array the available data models
*/
abstract protected function prepareModels();
/**
* Prepares the keys associated with the currently available data models.
* #param array $models the available data models
* #return array the keys
*/
abstract protected function prepareKeys($models);
/**
* Returns a value indicating the total number of data models in this data provider.
* #return integer total number of data models in this data provider.
*/
abstract protected function prepareTotalCount();
/**
* Prepares the data models and keys.
*
* This method will prepare the data models and keys that can be retrieved via
* [[getModels()]] and [[getKeys()]].
*
* This method will be implicitly called by [[getModels()]] and [[getKeys()]] if it has not been called before.
*
* #param boolean $forcePrepare whether to force data preparation even if it has been done before.
*/
public function prepare($forcePrepare = false)
{
if ($forcePrepare || $this->_models === null) {
$this->_models = $this->prepareModels();
}
if ($forcePrepare || $this->_keys === null) {
$this->_keys = $this->prepareKeys($this->_models);
}
}
/**
* Returns the data models in the current page.
* #return array the list of data models in the current page.
*/
public function getModels()
{
$this->prepare();
return $this->_models;
}
/**
* Sets the data models in the current page.
* #param array $models the models in the current page
*/
public function setModels($models)
{
$this->_models = $models;
}
/**
* Returns the key values associated with the data models.
* #return array the list of key values corresponding to [[models]]. Each data model in [[models]]
* is uniquely identified by the corresponding key value in this array.
*/
public function getKeys()
{
$this->prepare();
return $this->_keys;
}
/**
* Sets the key values associated with the data models.
* #param array $keys the list of key values corresponding to [[models]].
*/
public function setKeys($keys)
{
$this->_keys = $keys;
}
/**
* Returns the number of data models in the current page.
* #return integer the number of data models in the current page.
*/
public function getCount()
{
return count($this->getModels());
}
/**
* Returns the total number of data models.
* When [[pagination]] is false, this returns the same value as [[count]].
* Otherwise, it will call [[prepareTotalCount()]] to get the count.
* #return integer total number of possible data models.
*/
public function getTotalCount()
{
if ($this->getPagination() === false) {
return $this->getCount();
} elseif ($this->_totalCount === null) {
$this->_totalCount = $this->prepareTotalCount();
}
return $this->_totalCount;
}
/**
* Sets the total number of data models.
* #param integer $value the total number of data models.
*/
public function setTotalCount($value)
{
$this->_totalCount = $value;
}
/**
* Returns the pagination object used by this data provider.
* Note that you should call [[prepare()]] or [[getModels()]] first to get correct values
* of [[Pagination::totalCount]] and [[Pagination::pageCount]].
* #return Pagination|boolean the pagination object. If this is false, it means the pagination is disabled.
*/
public function getPagination()
{
if ($this->_pagination === null) {
$this->setPagination([]);
}
return $this->_pagination;
}
/**
* Sets the pagination for this data provider.
* #param array|Pagination|boolean $value the pagination to be used by this data provider.
* This can be one of the following:
*
* - a configuration array for creating the pagination object. The "class" element defaults
* to 'yii\data\Pagination'
* - an instance of [[Pagination]] or its subclass
* - false, if pagination needs to be disabled.
*
* #throws InvalidParamException
*/
public function setPagination($value)
{
if (is_array($value)) {
$config = ['class' => Pagination::className()];
if ($this->id !== null) {
$config['pageParam'] = $this->id . '-page';
$config['pageSizeParam'] = $this->id . '-per-page';
}
$this->_pagination = Yii::createObject(array_merge($config, $value));
} elseif ($value instanceof Pagination || $value === false) {
$this->_pagination = $value;
} else {
throw new InvalidParamException('Only Pagination instance, configuration array or false is allowed.');
}
}
/**
* Returns the sorting object used by this data provider.
* #return Sort|boolean the sorting object. If this is false, it means the sorting is disabled.
*/
public function getSort()
{
if ($this->_sort === null) {
$this->setSort([]);
}
return $this->_sort;
}
/**
* Sets the sort definition for this data provider.
* #param array|Sort|boolean $value the sort definition to be used by this data provider.
* This can be one of the following:
*
* - a configuration array for creating the sort definition object. The "class" element defaults
* to 'yii\data\Sort'
* - an instance of [[Sort]] or its subclass
* - false, if sorting needs to be disabled.
*
* #throws InvalidParamException
*/
public function setSort($value)
{
if (is_array($value)) {
$config = ['class' => Sort::className()];
if ($this->id !== null) {
$config['sortParam'] = $this->id . '-sort';
}
$this->_sort = Yii::createObject(array_merge($config, $value));
} elseif ($value instanceof Sort || $value === false) {
$this->_sort = $value;
} else {
throw new InvalidParamException('Only Sort instance, configuration array or false is allowed.');
}
}
/**
* Refreshes the data provider.
* After calling this method, if [[getModels()]], [[getKeys()]] or [[getTotalCount()]] is called again,
* they will re-execute the query and return the latest data available.
*/
public function refresh()
{
$this->_totalCount = null;
$this->_models = null;
$this->_keys = null;
}
}
The code above is the BaseDataProvider for yii2. My question is how i can set the _models and _keys in yii2? Which file do i need to change to link to that? Sorry i am quite new to yii. Please provide an example if possible thank you.
That what's You pasted here is abstract Yii2 class, which You should NEVER edit.
To use this thing i suggest You to read about ActiveDataProvider here: Docs
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
]);
Here's an example how to use it, first line defines data which will be used to populate ActiveDataProvider (it's a SQL query), and then You create ActiveDataProvider instance with query as config parameter.
It is known that after creating a new model, there is a function to change the table used by the model.
For example,
$example_model = new ExampleModel;
$example_model->setTable('myTable_'.$some_other_variable);
However, if I am finding record from table, is there a way to choose the table before querying the database?
i.e. something like this
$example_model = ExampleModel::setTable('myTable_'.$some_other_variable)->where('myColumn', $variable_to_be_compared)->get();
(Noticed that the following line is not correct. I will says setTable is not a static method)
I have some custom function in my model, so I would prefer not to use DB::table('myTable_'.$some_other_variable).
The problem with the upstream setTable() method is that it returns nothing (void) so even you manage to call it you won't be able to chain it with other methods unless you override it.
// File: ExampleModel.php
/**
* Set the table associated with the model.
*
* #param string $table
* #return self
*/
public function setTable($table)
{
$this->table = $table;
return $this;
}
Then you can do something like this
$example_model = with(new ExampleModel)->setTable('myTable_'.$some_other_variable)->where('myColumn', $variable_to_be_compared)->get();
But since that solution involves writing the method, you could write instead a new static method for the task so you don't need to use helpers
/**
* Change the table associated with the model.
*
* #param string $table
* #param array $attributes
* #return self
*/
public static function changeTable($table, $attributes = [])
{
$instance = new static($attributes);
$instance->setTable($table);
return $instance;
}
Which can be use
$example_model = ExampleModel::changeTable('myTable_'.$some_other_variable)->where('myColumn', $variable_to_be_compared)->get();