I want to make a friendlist using ManyToMany self-referencing.
I followed this link and it seemms to be good. But Now, what Action should I have in my controller to :
1- get All myFriends / or all all friend of current user
2- add a firend, using a link such as "Add friend"
thank you for your time and answers
in your link my friends is a doctrine array collection, to get the friends of a user just iterate on it and to add a friend just add a friend onto this collection and save the entity (with the entity manager), maybe you ll need to add a cascade persist on the collection to add a new user as friend.
you have to add some methods like getMyFriends, addFriend and removeFriend
<?php
/** #Entity */
class User
{
// ...
/**
* Many Users have Many Users.
* #ManyToMany(targetEntity="User", mappedBy="myFriends")
*/
private $friendsWithMe;
/**
* Many Users have many Users.
* #ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
* #JoinTable(name="friends",
* joinColumns={#JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#JoinColumn(name="friend_user_id", referencedColumnName="id")}
* )
*/
private $myFriends;
public function __construct() {
$this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
$this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getMyFriends(){
return $this->myFriends;
}
public function addFriend(User $friend){
$this->myFriends->add($friend);
}
public function removeFriend(User $friend){
$this->myFriends->removeElement($friend);
}
}
in your controller you have to implement an action with
$currentUser= $this->get('security.context')->getToken()->getUser();
$myFriends = $currentUser->getMyfriends();
$this->render('your-template.html.twig', array(
'myFriends' => $myFriends,
));
and in your twig template
<h1>My friends</h1>
<ul>
{% for friend in myFriends %}
<li>{{ friend.username }}</li>
{% endfor %}
</ul>
Related
My Post Model like:
namespace App;
use Illuminate\Database\Eloquent\Model;
class **Post** extends Model
{
protected $table = 'posts';
protected $guarded = ['id'];
public function user(){
return $this->belongsTo('App\User','user_id','id');
}
}
And User Model like:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $guarded = ['id'];
public function userType(){
return $this->belongsTo('App\User','user_type_id','id');
}
}
Now if I call the following in my controller:
$posts = \App\Post::with('user.userType')->where('status', 1)->get();
It returns all the posts for posts.status = 1, with users table data and also user_type.
What should I do??, if I want to set a where condition for users table or for user_types table like: where('user.id', 5) or where('user_types.id', 1).
Is it possible?? if yes please answer.
Thanks in advance.
i am beginner in la-ravel,problem in work on model how be work on project.
firstly used the api.php to link the page
Route::any('/user',['uses'=>'PagesController#my']);
create the controller
public function my(Request $request){
$val=validator::make($request->all(),[
'id'=>'required',
'name'=>'required',
'email'=>'required',
'mobile'=>'required'
]);
//return 'rahul';
return response()->json([$val]);
}
model is link to the controller
use App\rahul;
use Validator;
create the model page design
class rahul extends Model{
protected $table = "display";
public function my($data)
{
$save = new rahul;
$save->id = $data['id'];
$save->name = $data['name'];
$save->email = $data['email'];
$save->mobile = $data['mobile'];
$save->save();
return $save->id;
}
}
and,last step will done it create the database like
enter image description here
database name is lara2 and table name display simple page design
but problem how to model be used
Route::get('first', 'ApiController#first')->name('first');
Route::post('store', 'ApiController#store')->name('store');
using the code in api.php
and next step model is create
php artisan make: model Article
model page
class Article extends Model{ protected $fillable = ['name', 'email'];}
next step create the controller
controller page (apicontroller)
public function first(){
return view('first');
}
public function store(Request $request)
{
$article = Article::create($request->all());
return response()->json($article, 201);
}
blade page web page design
<form method="POST" action="store">
{{csrf_field()}}
<input type="text" name="name">
<input type="email" name="email">
<input type="submit" name="submit"></form>
migration is create Article table name connection
public function up()
{
Schema::create('Articles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Articles');
}
I have two entities User and Article with many-to-many relation as Article can have many authors.
class User
{
/** #var string */
public $name;
/** #var Collection<Article> */
public $articles;
}
class Article
{
/** #var string */
public $title;
/** #var Collection<User> */
public $authors;
}
How I can find all Articles with specified (co)author using DQL?
Use MEMBER OF expression.
Your DQL query could like like
SELECT art FROM Article art WHERE :user MEMBER OF art.authors
or using query builder
$queryBuilder = $repository->createQueryBuilder("art");
$queryBuilder->where(":user MEMBER OF art.authors");
Alternatively you can join and filter collection
SELECT art FROM Article art JOIN art.authors aut WHERE aut = :user
or
$queryBuilder = $repository->createQueryBuilder("art");
$queryBuilder->join("art.authors", "aut");
$queryBuilder->where("aut = :user");
Use Query Builder
Summary
$qb->expr()->isMemberOf(':user', 'a.authors')
Solution
src/Repository/ArticleRepository.php
/**
* #param User $author
* #return Article[] List of articles filtered by $author
*/
public function findByAuthor(User $author): array
{
$qb = $this->createQueryBuilder('a');
$qb->setParameter('user', $author);
$qb->where($qb->expr()->isMemberOf(':user', 'a.authors'));
return $qb->getQuery()->getResult();
}
Example use
src/Controller/ArticleController.php
/**
* #Route("/article/{id<\d+>}", name="show-articles-by-author")
* #param ArticleRepository $articleRepository
* #param User $author
*/
public function showArticlesFromAuthor(ArticleRepository $articleRepository, User $author)
{
$articles = $articleRepository->findByAuthor($author);
return $this->render('articles.html.twig', [
'articles' => $articles,
'author' => $author->getName()
]);
}
templates/articles.html.twig
<h1>Articles from {{ author }}</h1>
<li>
{% for article in articles %}
<ul>
{{ article.title }}
</ul>
{% endfor %}
</li>
I've got a problem with my multi select fields. Here is the code:
In the Entity class
/**
* #Annotation\Options({ "disable_inarray_validator":"true", "label":"Bound Checkpoints", "target_class":"Checkpoint","property":"name"})
* #Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect")
* #Annotation\Attributes({ "multiple":"true", "class":"form-control"})
* #Annotation\Required(false)
* #ORM\ManyToMany(targetEntity="Checkpoint", inversedBy="affectedByCheckpoints")
*/
private $boundCheckpoints;
public function __construct() {
$this->boundCheckpoints= new \Doctrine\Common\Collections\ArrayCollection();
}
public function addBoundCheckpoints( $items)
{
foreach($items as $item)
{
$this->boundCheckpoints->add($item);
}
}
public function removeBoundCheckpoints($items)
{
foreach($items as $item)
{
$this->boundCheckpoints->removeElement($item);
}
}
My issue is: if I set some stuff into the field, it save it well. If I remove one, still working. But if I remove all items I set and fire the form, the removeBoundCheckpoints method is never called.
I tried to set a required validator to the form, but If I do that, I've got a validation issue.
Any ideas ?
solved by adding this workaround into the template.
{% if field.getAttribute('multiple') == 'multiple' or field.getAttribute('multiple') == 'true' %}
<input type="hidden" name="{{field.getName()}}" value="" />
{% endif %}
{{formElement(field) }}
I want to create a <select> without using the helpers (because the select helper is generating a lot of html)
So, I get a list of cities from the Controller like:
public static List<City> getAllSortedByNameAsc() {
List<City> cities = new ArrayList<City>();
cities.addAll(City.find.orderBy("name").findList());
return cities;
}
In my template, I create the options with this code:
#cities.map { city =>
<option value="#city.id">#city.name</option>
}
which works, but I also want to have the chosen city as selected value. I tried several things like this:
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value == city.id){selected}">#city.name</option>
}
But that doesn't work. Can anyone give me a hint?
Configuration File: application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
Controller Class => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.data.Form;
import views.html.*;
public class Application extends Controller {
final static Form<City> cityForm = form(City.class);
public static Result index() {
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
City city=City.get(2L);
return ok(index.render(cityForm.fill(city),City.all()));
}
}
Model Class => City.java:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.ebean.Model;
import java.util.List;
import com.avaje.ebean.validation.NotNull;
#Entity
public class City extends Model{
#Id
public Long id;
#NotNull
public String name;
public static Finder<Long, City> find = new Finder(Long.class, City.class);
public static City get(Long id){
return find.byId(id);
}
public static List<City> all() {
return find.all();
}
}
Template File => index.scala.html
#(cityForm: Form[City],cities: List[City])
<!DOCTYPE html>
<html>
<head><title></title></head>
<body>
<div>
<select>
#for(city <- cities){
<option value="#city.id" #{if(city.id.toString().equals(cityForm("id").value)) "selected='selected'"}/>#city.name</option>
}
</select>
</div>
</body>
</html>
I'm not positive about how the type mapping is working, but I would try
#cities.map { city =>
<option value="#city.id" selected="#if(offerForm("city.id").value.equals(city.id)){selected}">#city.name</option>
}
rather than using the == operator.
You should also consider whether the helper has a good reason for generating all that HTML. It's generally a pretty smart framework.