I want to have _id in the database but want to output id when doing a query.
How can I achieve it?
You can try this (using an Accessor) :
Model
public function getIdAttribute() {
return $this->attributes['_id'];
}
Controller test
$user = User::find(1);
// this will call getIdAttribute which will return the `_id`
dd($user->id);
You can also override toArray() method if you want to show it :
Model
// ..
// getIdAttribute()
// ..
public function toArray()
{
$array = parent::toArray();
$array['id'] = $this->id;
unset($array['_id']);
return $array;
}
Controller Test
$user = User::find(1);
dd($user->toArray());
Another way to do this is using Transformers (http://fractal.thephpleague.com/transformers/). There is a service provider for Laravel here (https://github.com/gathercontent/laravel-fractal).
It will do that in a elegant way :)
Of course, if you need to do only with "id" field, I'll do like zorx told:
public function getIdAttribute() {
return $this->attributes['_id'];
}
But you'll probably put that in some BaseModel or abstractModel class, a parent for you models who need this.
Related
I am new to laravel. I am facing a very weird problem. I have a model comment which is related to User model in laravel.
The Relationships are defined as such
//App\User model
public function comments()
{
return $this->hasMany('App\comment');
}
And
//App\Comment model
public function User()
{
return $this->belongsTo('App\User');
}
now when i am fetching user and comment s using find and with it is returning data for all the users in the table. My code is like this: App\User::find(1)->with('comments')->get(); Can some one tell me what am doing wrong?
Try something like this
$comments=App\User::whereId(1)->comments->get();
This should load every comment associated with user with ID 1
//App\User model
public function comments() {
return $this->hasMany('App\comment','user_id','id');
}
//In your controller
use App\User;
$comment = User::where('id',2)->comments->get();
//I hope It's work for you!
public function aroundGetData(\Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider $subject, callable $proceed)
{
// what is do here
}
it feels that did not dive deep enough,
For global use easies way is to use addField or even alter SQL to add data from some related table.
public function aroundGetData(\Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider $subject, callable $proceed)
{
$subject->addField('field', 'alias'); // alias is optional
$collection = $subject->getCollection(); // Here you have access to all public methods of collection.
$select = $collection->getSelect(); // You can do whatever you want with Zend_DB_Select here
return $proceed();
}
DataProvider has addField and addFilter method uses Product Collection under the hood.
In my Lumen project I use a many to many relationship like this:
class Item{
protected $appends = ['order'];
public getOrderAttribute(){
return $this->pivot->order;
}
public function collections(){
return $this->belongsToMany(Collection)->withTimestamps()->withPivot('order');
}
}
and then in the collection
class Collection{
public function items(){
return $this->belongsToMany(Item)->withTimestamps()->withPivot('order')';
}
}
then I try to insert a new item in a collection like this:
addItem(Request $req, $id){ <- is for collection
$item = new Item();
$item->save();
$collection = Collection::findOrFail($id);
$collection->items()->attach($item, ['order' => $req->input('order')]);
return $item;
this result in Trying to get property of non-object
The data gets stored in the database succesfully and correctly.
I have tried switching up the attach on collections() and on items() but that doenst change anything.
I have tried to renew the item value like this: Item::findOrFail($item->id)
still results in the same error.
Abd when I refresh the page I get the correct data.
I'm new to Laravel-Mongodb, trying to get result by parameter but it's not working
Model:
use Jenssegers\Mongodb\Model as Eloquent;
class Customer extends Eloquent {
protected $connection = 'mongodb';
protected $collection = 'Customer';
}
Controller:
class AdminController extends Controller
{
public function index() {
return Customer::all();
}
public function show($id) {
return Customer::find($id);
}
}
It's alright for index() but it will return empty for show($id), it will work if using:
return Customer::find(1);
I'm not sure why it's not working with parameter, am I missing something?
You need to add one protected variable in your model like below
protected $primaryKey = “customerId”
You can add your own primary key to this variable but if you won’t add this line in model, model will by default take _id as your primary key and _id is autogenerated mongodb’s unique id.
Thats the reason why you are not able to get record by id.
1 is not a valid ObjectId. Try to find a valid ID with a tool like Robomongo or just list your customers with your index method to find out what the IDs are.
The query should look more like this:
return Customer::find("507f1f77bcf86cd799439011");
You can read more about MongoDBs ObjectId here:
https://docs.mongodb.org/manual/reference/object-id/
sBased on Doctrine documentation $qb->getQuery()->execute(); will return a cursor for you to iterator over the results but $qb->find($criteria); returns the actual found Documents.
I am using symfony2 MongoDBbundle and I would like to avoid iterating over the result set in Repository classes.
// Returns Product Document
$entity = $this->get('doctrine_mongodb')
->getRepository("MyBundle:Product")
->findOneBy(array('title' => 'somthing'));
// Returns Cursor
$entity = $this->get('doctrine_mongodb')
->getRepository("MyBundle:Product")
->customFunctionWithcreateQueryBuilder(array('title' => 'somthing'));
How can I make cutomFunctionWithcreateQueryBuilder() returns the same class/result as findOneBy?
Also How can I make execute() returns all embedded documents?
EDIT
Content Of cutomFunctionWithcreateQueryBuilder:
class ProductRepository extends DocumentRepository {
public function customFunctionWithcreateQueryBuilder($param, $hydrate = true) {
$query = $this->createQueryBuilder()
->select()
->hydrate($hydrate);
if (isset($param['unique_id'])) {
$query->field('id')->equals($param['unique_id']);
}
return $query->getQuery()->execute();
}
}
You can use getSingleResult() if you want only one result and set eagerCursor to true to get all data at once. In example:
[...]
if (isset($param['unique_id'])) {
$query->field('id')->equals($param['unique_id']);
}
return $query->eagerCursor(true)->getQuery()->getSingleResult();
[...]