logo
Tags down

shadow

Get all relations through manyToMany relation


By : VG7
Date : September 17 2020, 08:00 AM
Hope this helps as per your relationship, you can fetch every accounts of a user with every items on each of those accounts as follows:
code :
auth()->user()->accounts()->with('items')->get();
//Account.php
public function items()
{
  return $this->hasMany( Item::class );
}


Share : facebook icon twitter icon

Django ManyToMany relation to 'self' without backward relations


By : Jeri Team
Date : March 29 2020, 07:55 AM
To fix the issue you can do My understanding of the question is that the ManyToMany relationship should be one way, in that if the following is true:
code :
             --------------           ----------------
             | mymodelone |---------->|  mymodeltwo  |
             --------------     |     ----------------
                                |
                                |     ----------------
                                ----->| mymodelthree |
                                      ----------------
             --------------           ----------------
             | mymodelone |<-----/----|  mymodeltwo  |
             --------------           ----------------

             --------------           ----------------
             | mymodelone |<-----/----| mymodelthree |
             --------------           ----------------
$ python ./manage.py startapp stuff
...
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'stuff'
)
....
from django.db import models

class MyModel(models.Model):
    stuff = models.ManyToManyField('self', related_name = 'combined+', symmetrical=False, blank = True, null = True, verbose_name = "description")

    def __unicode__(self):
        return "MyModel%i" % self.id
$ python ./manage.py syncdb
Creating tables ...
Creating table stuff_mymodel_stuff
Creating table stuff_mymodel
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
$ python ./manage.py shell
>>> from stuff.models import MyModel
>>> MyModel().save()
>>> MyModel().save()
>>> MyModel().save()
>>> MyModel.objects.all()
[<MyModel: MyModel1>, <MyModel: MyModel2>, <MyModel: MyModel3>]
>>> m1 = MyModel.objects.get(pk=1)
>>> m2 = MyModel.objects.get(pk=2)
>>> m3 = MyModel.objects.get(pk=3)
>>> m1.stuff.all()
[]
>>> m1.stuff.add(m2)
>>> m1.stuff.add(m3)
>>> m1.stuff.all()
[<MyModel: MyModel2>, <MyModel: MyModel3>]
>>> m2.stuff.all()
[]
>>> m3.stuff.all()
[]
>>> 
from django.db import models

class MyModel(models.Model):
    stuff = models.ManyToManyField('self', related_name = 'combined+')

def __unicode__(self):
    return "MyModel%i" % self.id
>>> MyModel().save()
>>> MyModel().save()
>>> MyModel.objects.all()
[<MyModel: MyModel1>, <MyModel: MyModel2>, <MyModel: MyModel3>, <MyModel: MyModel4>, <MyModel: MyModel5>]
>>> m4 = MyModel.objects.get(pk=4)
>>> m5 = MyModel.objects.get(pk=5)
>>> m4.stuff.add(m5)
>>> m4.stuff.all()
[<MyModel: MyModel5>]
>>> m5.stuff.all()
[<MyModel: MyModel4>]
>>> from stuff.models import MyModel
>>> MyModel().save()
>>> MyModel().save()
>>> MyModel.objects.all()
[<MyModel: MyModel1>, <MyModel: MyModel2>, <MyModel: MyModel3>, <MyModel: MyModel4>, <MyModel: MyModel5>, <MyModel: MyModel6>, <MyModel: MyModel7>]
>>> m6 = MyModel.objects.get(pk=6)
>>> m7 = MyModel.objects.get(pk=7)
>>> m6.stuff.all()
[]
>>> m7.stuff.all()
[]
>>> m6.stuff.add(m7)
>>> m6.stuff.all()
[<MyModel: MyModel7>]
>>> m7.stuff.all()
[]
>>> m5 = MyModel.objects.get(pk=5)
>>> m4 = MyModel.objects.get(pk=4)
>>> m4.stuff.all()
[<MyModel: MyModel5>]
>>> m5.stuff.all()
[<MyModel: MyModel4>]
             -----------------           -----------------------
             | stuff_mymodel |---------->| stuff_mymodel_stuff |
             -----------------           -----------------------
                      ^                              |
                      |                              |
                      --------------------------------
mysql> describe stuff_mymodel;
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.00 sec)

mysql> describe stuff_mymodel_stuff;
+-----------------+---------+------+-----+---------+----------------+
| Field           | Type    | Null | Key | Default | Extra          |
+-----------------+---------+------+-----+---------+----------------+
| id              | int(11) | NO   | PRI | NULL    | auto_increment |
| from_mymodel_id | int(11) | NO   | MUL | NULL    |                |
| to_mymodel_id   | int(11) | NO   | MUL | NULL    |                |
+-----------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
$ python ./manage.py sql stuff
    BEGIN;
CREATE TABLE `stuff_mymodel_stuff` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `from_mymodel_id` integer NOT NULL,
    `to_mymodel_id` integer NOT NULL,
    UNIQUE (`from_mymodel_id`, `to_mymodel_id`)
)
;
CREATE TABLE `stuff_mymodel` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY
)
;
ALTER TABLE `stuff_mymodel_stuff` ADD CONSTRAINT `from_mymodel_id_refs_id_7fa00238` FOREIGN KEY (`from_mymodel_id`) REFERENCES `stuff_mymodel` (`id`);
ALTER TABLE `stuff_mymodel_stuff` ADD CONSTRAINT `to_mymodel_id_refs_id_7fa00238` FOREIGN KEY (`to_mymodel_id`) REFERENCES `stuff_mymodel` (`id`);
COMMIT;
mysql> select * from stuff_mymodel_stuff;
+----+-----------------+---------------+
| id | from_mymodel_id | to_mymodel_id |
+----+-----------------+---------------+
|  1 |               1 |             2 |
|  2 |               1 |             3 |
|  3 |               4 |             5 |
|  4 |               5 |             4 |
|  5 |               6 |             7 |
+----+-----------------+---------------+
5 rows in set (0.00 sec)
    # If the ManyToMany relation has an intermediary model,
    # the add and remove methods do not exist.
    if rel.through._meta.auto_created:
        def add(self, *objs):
            self._add_items(self.source_field_name, self.target_field_name, *objs)

            # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table
            if self.symmetrical:
                self._add_items(self.target_field_name, self.source_field_name, *objs)
        add.alters_data = True

Select count() in Doctrine DQL with left join manyToMany unidirectional relation where user does NOT have relation speci


By : ranvi
Date : March 29 2020, 07:55 AM
To fix the issue you can do Situaction: I am trying to select count() in DQL for users NOT in specific group. , The only way I managed to do it in DQL is use subquery:
code :
SELECT COUNT(u)
FROM RAZUserBundle:User u
WHERE u.id NOT IN (
    SELECT u2.id
    FROM RAZUserBundle:User u2
    JOIN u2.groups g WITH g.id = 70
)

django admin list_display from two tables, no relations like foreign key or manytomany relation available


By : Atalo Habtie
Date : March 29 2020, 07:55 AM
may help you . You can use Cache Framework. It is very easy:
code :
# coding: utf-8
from django.core.cache import cache
from django.contrib import admin

from .models import MeasuredController, MeasuredGrid


class MeasuredControllerAdmin(admin.ModelAdmin):
    list_display = ("grid_status", "grid_power")

    STATUS_CHOICES = {
        0: "Outage",
        1: "No Outage",
    }

    def grid_status(self, obj):
        mobj = self._get_mobj_data(obj)
        return mobj['status']
    grid_status.short_description = 'Grid Status'

    def grid_power(self, obj):
        mobj = self._get_mobj_data(obj)
        return mobj['power']
    grid_power.short_description = 'Grid Power[W]'

    def _get_mobj_data(self, obj):
        """Get a relevant MeasuredGrid object for a given MeasuredController"""

        data = cache.get('mobj_%s' % obj.pk)
        if data is not None:
            return data

        mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")

        status = None
        try:
            status = self.STATUS_CHOICES[int(mobj.status)], 2
        except: # <---------- Not the best decision. You probably need ValueError or KeyError
            pass

        data = {
            "id": mobj.pk,
            "power": mobj.power,
            "status": status,
        }

        cache.set('mobj_%s' % obj.pk, data) # the default timeout is 300 seconds

        return data

Doctrine2 ManyToMany relation using PostgreSQL: "SQLSTATE[42P01]: Undefined table: 7 ERROR: the relation does not e


By : Sneha
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , At last I found a solution to this problem. You need to edit (manually) the joinTable name on the ORM configuration, which in my case is a Yaml file, adding the Postgres schema the associative table belongs to:
Entity.orm.yml
code :
manyToMany:
    idBaseModel:
        targetEntity: BaseModel
        cascade: {  }
        fetch: LAZY
        mappedBy: null
        inversedBy: idMachineTable
        joinTable:
            name: <NAME_OF_YOUR_SCHEMA>.<NAME_OF_THE_TABLE>
            joinColumns:
                -
                    name: id_machine_table
                    referencedColumnName: id
            inverseJoinColumns:
                -
                    name: id_base_model
                    referencedColumnName: id
        orderBy: null
lifecycleCallbacks: {  }

ManyToMany relationship and the join table in relation ManyToMany with another Class


By : MrHaha
Date : March 29 2020, 07:55 AM
I wish this help you after searching a lot with no luck I decided to ask my question here, so I will start by giving an example to make things clear. , A simple example using JPA composite pks might be:
code :
@Entity
class A {
  @Id
  Integer id;
  @OneToMany(mappedBy="a")
  List<AB> abList;
}

@Entity
class B {
  @Id
  Integer id;
  @OneToMany(mappedBy="b")
  List<AB> abList;
}

@Entity
@IdClass(ABId.class)
class AB {
  @Id
  @ManyToOne
  public A a;
  @Id
  @ManyToOne
  public B b;
  @OneToMany(mappedBy="ab")
  List<ABC> abcList;
}

class ABId {
  public Integer a;
  public Integer b;
}

@Entity
@IdClass(ABCId.class)
class ABC {
  @Id
  @ManyToOne
  public AB ab;
  @Id
  @ManyToOne
  public C c;
  @ManyToMany
  List<D> dList;
}

class ABCId {
  public ABId ab;
  public Integer c;
}
Related Posts Related Posts :
  • How to upgrade Laravel from 5.7 to 5.8
  • Laravel Column already exists: 1060 Duplicate column name
  • How to display HTML if there are errors
  • change local data object on change of global state
  • How to customise the reset password link
  • How to make some blade templates can be accessed by 1 user but not by another users
  • In laravel 5.7 and vue.js search function doesn't work in my host
  • Usage Gate in verification routes
  • 404 error when calling api in laravel 6.4 with apache2 virtualhost
  • how to remove public from laravel6 url without renaming server.php into index.php
  • Laravel Socialite: Legacy People API has not been used in project
  • Wrongly update all the record after calling a function
  • composer require laravel/passport not working in laravel 5.8
  • How to change Laravel-Nova action name?
  • How to overwrite the laravel DatabaseManager method
  • laravel htaccess dont work in localhost server
  • Dropdown menu not working with Bootstrap 4 and Laravel 6
  • Redis connection [] has not been configured. - Connection property passed is empty
  • email/verify with VusJS SPA and Laravel
  • Laravel local vue component registration
  • how to use laravel resources for relationship both side
  • How to get the token value in the DB for notifications in Laravel
  • Multi-tenancy and custom features per tenant
  • Laravel lazy collection for huge data
  • Using Eloquent join results in incorrect id results
  • Show an attribute from other model in blade (Laravel)
  • Posting Form data with Guzzle always returns 404
  • How to keep user in the same page when register? (laravel)
  • How can i pass only one message for all fields
  • How to pass data from return()->redirect()->back()?
  • How to add `OR` operator to validation rule?
  • Not able to get complete query with like condition Laravel 6.5.2
  • Laravel updateOrCreate with where clause
  • How to create a custom Error 419: Page Expired in Laravel?
  • if else condition in routes laravel
  • Laravel client authentification with external Laravel passport lumen api
  • Laravel views folder structure for different designs
  • The GET method is not supported for this route. Supported methods: PATCH. when doing update
  • Laravel Homestead/Vagrant box error : The specified checksum type is not supported by Vagrant: sha512
  • Get value of nested array from json
  • how is it possible to dynamic route
  • Why does groupBy() work but Count() does not in laravel eloquent model function?
  • Update Method in Laravel
  • Hosting Laravel 5.7 project in Godaddy server
  • how do i solve the image upload issue of laravel while hosting it on shared hosting?
  • npm run watch does not reload on specific changes
  • not giving perfect result
  • how to get list of users who are not under belongsToMany relation under a table in laravel?
  • Issues with Database Seeder and Laravel
  • Transform Array to Object In Laravel
  • Declaration of App\Http\Requests\UserUpdateRequest::user() should be compatible with Illuminate\Http\Request::user($guar
  • Laravel blade override logo in layout depending on the view
  • Should I check in bootstrap/cache - Laravel 5.8?
  • Undefined variable: jobs in laravel
  • Redirect to another route with data Laravel 5.8
  • Best practice to create a user in table and invite them to login
  • Extract count of each status by month
  • Laravel Routing - Best way to differentiate routes with same format
  • Is it possible to create a second Laravel "api route" with a separate API KEY?
  • Weird php file under laravel5.8 public folder
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk