``` public function getContaCorrente()
{
return $this->hasOne(\app\models\ContaCorrente::className(), ['id' => 'conta_corrente_id']);
}```
Is it possible to add two attributes in the same get? For example, I have this get above and I want to join it with the get below, as they both look for the same table but different variables.
public function getContaCorrenteAdesao()
{
return $this->hasOne(\app\models\ContaCorrente::className(), ['id' => 'conta_corrente_adesao']);
}
Since this is a query builder you can do something like that:
public function getContaCorrenteAdesao()
{
return $this->hasOne(\app\models\ContaCorrente::className(), ['id' => 'conta_corrente_adesao'])->orWhere(['id' => 'conta_corrente_id']);
}
Related
Take the following sample Cart model. It has a CartItem "pivot record/table" which links it to Item.
class Cart extends ActiveRecord {
public function getCartItems() {
return $this
->hasMany(CartItem::class, ['cart_id' => 'id'])
->inverseOf('cart');
}
public function getItems($callback = null) {
return $this
->hasMany(Item::class, ['item_id' => 'id'])
->via('cartItems', $callback);
}
}
(Example #1) At this point I would be able to filter either by Item's activequery or CartItem's query like so:
$booksAddedToCartSinceYesterday = $cart
->getItems(function($cartItemQuery) {
$cartItemQuery->andWhere('cartItem.created_at > NOW()');
})
->andWhere(['item.category' => 'books']);
(Example #2) But how do I accomplish the same when I use the static find() method in combination with joinWith()? In the following example I am only able to filet by Item's ActiveQuery, but I no longer have any reference to the CartItem's ActiveQuery object:
$booksAddedToCartSinceYesterday = Cart::find()
->andWhere(['cart.user_id' => $some_user_id])
->joinWith([
'items' => function($itemQuery) {
$itemQuery->andWhere(['item.category' => 'books']);
},
]);
How do I modify the code above so that I am able to filter CartItem junction table records like I did in my example #1? How do I access the junction ActiveQuery object so that I can call $cartItemQuery->andWhere('cartItem.created_at > NOW()');?
you can pass any variable value in anonymous function with use keyword link below
make your magic code here for filter or any
->joinWith([
'items' => function($itemQuery) use ($var1,$var2){
$itemQuery->andWhere(['item.category' => 'books']);
$itemQuery->andWhere(['some_condition' => $var1]); <<<---------
},
]);
Been at this for a very long time and I can't get it right. Would be really thankful for some help. Thanks in advance!
Im trying to build a little clone of reddit some learning purpose.
I think these models is correct for what I'm trying to do. Im able to save a Subreddit to DB with user_id. But my problem is that I can't post to the post table since it's telling me it cannot find the subreddits_id column. Im seems like the method im trying to call should be working but it doesnt.
protected $fillable = ['title', 'link','content', 'post_picture', 'user_id', 'subreddit_id'];
//Functions
public function user () {
return $this->belongsTo(User::class);
}
public function subreddit() {
return $this->belongsTo(Subreddit::class);
}
public function comments () {
return $this->hasMany(Comment::class);
}
Above is my Post model
protected $guarded = [];
//Functions
public function user () {
return $this->belongsTo(User::class);
}
public function posts () {
return $this->hasMany(Post::class);
}
public function comments () {
return $this->hasMany(Comment::class);
}
Above is my Subreddit Model
public function posts () {
return $this->hasMany(Post::class);
}
public function subreddit() {
return $this->hasMany(Subreddit::class);
}
public function commments () {
return $this->hasMany(Comment::class);
}
Above is my User model
I think these models is correct for what I'm trying to do. Im able to save a Subreddit to DB with user_id. But my problem is that I can't post to the post table since it's telling me it cannot find the subreddits_id column. Im seems like the method im trying to call should be working but it doesnt.
The Store method looks like this:
public function store(Request $request)
{ $data = request()->validate([
'title' => 'required',
'link' => 'required',
'content' => 'required',
]);
$post = auth()->user()->posts()->create($data);
return redirect('/home');
}
I'm getting this error General error: 1364 Field 'subreddit_id' doesn't have a default value (SQL: insert into posts (title, link, content, user_id, updated_at, created_at) values (awe, ew, we, 2, 2020-04-01 17:41:29, 2020-04-01 17:41:29))
your $data only takes the parameters you specify for validation, But you did not include subreddit_id, It should be like this:
public function store(Request $request)
{ $data = request()->validate([
'title' => 'required',
'link' => 'required',
'content' => 'required',
'subreddit_id' => 'required|exist:subreddits,id'
]);
$post = auth()->user()->posts()->create($data);
return redirect('/home');
}
I have two models in laravel project Item and ItemImgs
Item.php
class Item extends Model
{
protected $appends = [
'photo',
];
public function imgs()
{
return $this->hasMany(ItemImage::class);
}
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src;
}
}
it's worked in views
dd(Item::all()); //worked
{{ $cane->photo}}; //worked
but when I try to get json
return response()->json([
'items' => Item::with('imgs')->get(),
]);
// not worked. Got timeout 500
You cannot use dot notation in PHP.
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src; // Dot notation is not allowed
}
but you've to use:
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img->src;
}
if what you're trying to do is to get the items that have imgs() then what you should do is query by relationship existence, as mentioned in the docs
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence
'items' => Item::has('imgs')->get()
It is not possible to refer to the linked model tables in attributes. It works in views but gives out a memory error when outputting an array through json.
public function getPhotoAttribute(){
$img = ItemImage::where('item', $this->id)-
>first();
}
It works that way, but it's not elegant.
i have table feedback and user, i am trying to show user's image on feedback page.
i am using grid view, this is my gridview.
[ 'attribute' => 'iduser.photo',
'headerOptions' => ['width' => '20px'],
'format' => 'image',
'value'=> function($data) { return $data->imageurl; },
],
and the model
public function getImageurl()
{
return \Yii::$app->request->BaseUrl.'/../../'.$this->hasOne(User::className(), ['photo' => 'photo']);
}
i get right url but the photoname is wrong the result is "photo", i want getting the data form entity photo?
Inside your model you should have a way to get the User related to your feedback like this:
public function getUser() {
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
Then your getImageurl method should look something like this:
public function getImageurl()
{
return \Yii::$app->request->BaseUrl.'/../../'.$this->user->photo;
}
I would recommend checking out Aliases, you can use them instead of \Yii::$app->request->BaseUrl. For example, this is the implementation i use to get a file url to show to the user:
public function getFileUrl() {
return Yii::getAlias('#web/uploads/'.$this->fileName);
}
I am attempting to filter a piece of input data but would like to do so without an anonymous function. The first example below works but the second example returns the error listed. I don't want the couple dozen lines of validation code sitting directly inside my rules so I would like a way to break it out (as in the second example I am trying to implement.
Example 1 (works but is not what I want to do)
public function rules()
{
return [
['roles', 'filter', 'filter' => function ($value) {
// Do some stuff to remove invalid roles
return $value;
}];
}
Example 2 (does not work but is what I would like to do)
public function rules()
{
return [
['roles', 'filter', 'filter' => 'checkRoles'],
];
}
public function checkRoles($value)
{
// Do some stuff to remove invalid roles
return $value;
}
Error returned for Example 2 above
call_user_func() expects parameter 1 to be a valid callback,
function 'validateRoles' not found or invalid function name
Why does the second example above not work? Or rather, more importantly, what do I need to change to get the second example to work?
You should use a valid callback, e.g. :
public function rules()
{
return [
['roles', 'filter', 'filter' => [$this, 'checkRoles']],
];
}
Read more : http://php.net/manual/language.types.callable.php
You may have to use a structure like this:
'filter' => array( $this, 'checkRoles' )